IO v7. Request и работа с ними
Описание
Request (класс запросов) - это вспомогательный класс Route, позволяющий работать с данными запроса.
Доступные функции
input()
input(
string|null $key = null,
mixed $default = null
): mixed
Получить параметр из любого источника (GET, POST, JSON, route)
| Аргумент функции | Тип | Описание | Обязательный |
|---|---|---|---|
$key | string, null | Ключ | Да |
$default | mixed | Значение по умолчанию | Нет |
Пример:
public function actionExample()
{
$name = $this->request->input('name', 'John');
$this->render('@app/example.twig', [
'name' => $name,
], 200);
}
all()
all(): array
Получить все параметры запроса
Пример:
public function actionExample()
{
$all = $this->request->all();
$this->render('@app/example.twig', [
'all' => $all,
], 200);
}
only()
only(
array|string $keys = []
): array
Получить только указанные поля
| Аргумент функции | Тип | Описание | Обязательный |
|---|---|---|---|
$keys | array, string | Ключи | Да |
Пример:
public function actionExample()
{
$name = $this->request->only('name');
$arr = $this->request->only(['age', 'email']);
$this->render('@app/example.twig', [
'name' => $name,
'arr' => $arr,
], 200);
}
except()
except(
array|string $keys = []
): array
Получить все кроме указанных полей
| Аргумент функции | Тип | Описание | Обязательный |
|---|---|---|---|
$keys | array, string | Ключи | Да |
Пример:
public function actionExample()
{
$arr = $this->request->except('password');
$arr2 = $this->request->except(['email', 'phone']);
$this->render('@app/example.twig', [
'arr' => $arr,
'arr2' => $arr2,
], 200);
}
query()
query(
string|null $key = null,
mixed $default = null
): mixed
Получить GET параметры
| Аргумент функции | Тип | Описание | Обязательный |
|---|---|---|---|
$key | string, null | Ключ | Да |
$default | mixed | Значение по умолчанию | Нет |
Пример:
public function actionExample()
{
$name = $this->request->query('name', 'John');
$this->render('@app/example.twig', [
'name' => $name,
], 200);
}
### post()
```php :line-numbers
post(
string|null $key = null,
mixed $default = null
): mixed
Получить POST параметры (включая JSON)
json()
json(
string|null $key = null,
mixed $default = null
): mixed
Получить JSON параметры (только если запрос с Content-Type: application/json)
| Аргумент функции | Тип | Описание | Обязательный |
|---|---|---|---|
$key | string, null | Ключ | Да |
$default | mixed | Значение по умолчанию | Нет |
Пример:
public function actionExample()
{
$arr = $this->request->json('arr', []);
$this->render('@app/example.twig', [
'arr' => $arr,
], 200);
}
route()
route(
string|null $key = null,
mixed $default = null
): mixed
Получить параметры из маршрута (из URL)
has()
has(
string $key = null
): bool
Проверить наличие параметра
file()
file(
string $key = null
): array|null
Получить загруженный файл
hasFile()
hasFile(
string $key = null
): bool
Проверить, был ли загружен файл
isJson()
isJson(): bool
Проверить тип запроса
method()
method(): string
Получить метод запроса
isMethod()
isMethod(
string $method
): bool
Проверить метод запроса
ip()
ip(): string
Получить IP адрес клиента
userAgent()
userAgent(): string
Получить User-Agent
url()
url(): string
Получить URL запроса
path()
path(): string
Получить базовый URL (без query string)
Работа с разными источниками данных
GET параметры (query string)
// URL: /users?page=2&limit=20
$page = $this->query('page', 1); // 2
$limit = $this->query('limit', 10); // 20
$allGet = $this->query(); // ['page' => 2, 'limit' => 20]
POST параметры (form-data, x-www-form-urlencoded)
// Обычная форма
$name = $this->post('name');
$allPost = $this->post(); // все POST данные
JSON запросы (Content-Type: application/json)
// Когда фронтенд шлет JSON (axios, fetch)
$data = $this->json(); // весь JSON объект
$name = $this->json('name'); // конкретное поле
$value = $this->input('name'); // тоже работает!
Параметры маршрута (из URL)
// Маршрут: /user/{id}/post/{postId}
public function actionView($id, $postId)
{
$userId = $this->route('id'); // то же что и $id
$postId = $this->route('postId'); // то же что и $postId
$allRoute = $this->route(); // ['id' => 123, 'postId' => 456]
}
Работа с файлами
public function actionUpload()
{
// Проверить, загружен ли файл
if ($this->hasFile('avatar')) {
$file = $this->file('avatar');
// Информация о файле
$name = $file['name']; // оригинальное имя
$tmp = $file['tmp_name']; // временный путь
$size = $file['size']; // размер в байтах
$error = $file['error']; // код ошибки
// Переместить файл
move_uploaded_file($tmp, '/path/to/' . $name);
}
// Поддержка вложенных полей (files[avatar][main])
$file = $this->file('avatar.main');
}
Информация о запросе
public function actionInfo()
{
// Метод запроса
$method = $this->method(); // GET, POST, PUT, DELETE
// Проверка метода
if ($this->isMethod('POST')) {
// ...
}
// Тип запроса
if ($this->isJson()) {
// это JSON запрос
}
// IP клиента
$ip = $this->request->ip();
// User-Agent
$ua = $this->request->userAgent();
// URL
$url = $this->request->url(); // полный URL с query
$path = $this->request->path(); // только путь без query
}
Прямой доступ к объекту Request
В любой момент вы можете получить доступ к объекту Request напрямую:
public function actionSomething()
{
$request = $this->request;
// Все методы доступны
$all = $request->all();
$json = $request->json();
$files = $request->file('avatar');
}
Примеры
Пример 1: REST API с JSON
<?php
namespace App\Routes;
use IO\Route;
class ApiRoute extends Route
{
public function actionCreate()
{
// Валидация
$required = ['name', 'email'];
foreach ($required as $field) {
if (!$this->has($field)) {
return $this->json([
'error' => "Field {$field} is required"
], 400);
}
}
// Получение данных (работает и для JSON, и для form-data)
$data = $this->only(['name', 'email', 'phone']);
// Сохранение в БД
$id = $this->saveToDatabase($data);
return $this->json([
'success' => true,
'id' => $id,
'received' => $data
]);
}
public function actionUpdate($id)
{
// Частичное обновление (PATCH)
$data = $this->input(); // все поля
// Исключаем защищенные поля
$data = $this->except(['id', 'role']);
return $this->json(['updated' => true]);
}
}
Пример 2: Загрузка файла с метаданными
public function actionUploadFile()
{
// Проверяем метод
if (!$this->isMethod('POST')) {
return $this->json(['error' => 'Method not allowed'], 405);
}
// Получаем метаданные из JSON или POST
$description = $this->input('description', '');
$tags = $this->input('tags', []);
// Получаем файл
if (!$this->hasFile('document')) {
return $this->json(['error' => 'No file uploaded'], 400);
}
$file = $this->file('document');
// Проверка типа файла
$allowed = ['pdf', 'doc', 'docx'];
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
return $this->json(['error' => 'File type not allowed'], 400);
}
// Сохраняем файл
$newName = uniqid() . '.' . $ext;
move_uploaded_file($file['tmp_name'], UPLOAD_PATH . '/' . $newName);
return $this->json([
'success' => true,
'filename' => $newName,
'description' => $description,
'tags' => $tags
]);
}
Пример 3: Фильтрация и валидация
public function actionSearch()
{
// GET параметры с значениями по умолчанию
$page = $this->query('page', 1);
$limit = $this->query('limit', 20);
$sort = $this->query('sort', 'created_at');
$order = $this->query('order', 'desc');
// Фильтры из POST (могут быть сложными)
$filters = $this->post('filters', []);
// Ограничиваем максимальный лимит
$limit = min($limit, 100);
// Валидация порядка сортировки
if (!in_array($order, ['asc', 'desc'])) {
$order = 'desc';
}
return $this->json([
'page' => $page,
'limit' => $limit,
'sort' => $sort,
'order' => $order,
'filters' => $filters
]);
}