Определение маршрутов IO7
Внимание
Данная статья документации написана нейросетью. Возможны некоторые расхождения и неточность информации!
Регистрация маршрутов
Через App::add_route()
$app->add_route(array $route_info): void
Ключи $route_info:
| Ключ | Тип | Значение по умолчанию | Обязателен | Описание |
|---|---|---|---|---|
url | string | — | Да | URL-паттерн (напр. /users/:id) |
match | string | null | Нет | Regex-паттерн (авто из url) |
type | string[] | ['get'] | Нет | HTTP-методы |
class_name | string | null | Нет | Класс-обработчик |
method | string | — | Да | Метод обработчик |
name | string | null | Нет | Имя маршрута |
middleware | string[]|string | [] | Нет | Middleware классы |
cors | array | [] | Нет | CORS конфигурация |
nosession | bool | false | Нет | Не создавать сессию |
Примеры
// GET /users
$app->add_route([
'url' => '/users',
'type' => ['get'],
'class_name' => \App\Routes\UserRoute::class,
'method' => 'index',
]);
// GET|POST /users/:id
$app->add_route([
'url' => '/users/:id',
'type' => ['get', 'post'],
'class_name' => \App\Routes\UserRoute::class,
'method' => 'show',
]);
// CRUD маршруты
$app->add_route(['url' => '/api/products', 'type' => ['get'], 'method' => 'list']);
$app->add_route(['url' => '/api/products/:id', 'type' => ['get'], 'method' => 'get']);
$app->add_route(['url' => '/api/products', 'type' => ['post'], 'method' => 'create']);
$app->add_route(['url' => '/api/products/:id', 'type' => ['put'], 'method' => 'update']);
$app->add_route(['url' => '/api/products/:id', 'type' => ['delete'], 'method' => 'delete']);
// С middleware
$app->add_route([
'url' => '/admin/users',
'type' => ['get'],
'class_name' => \App\Routes\AdminRoute::class,
'method' => 'users',
'middleware' => [\IO\Middlewares\AuthMiddleware::class],
]);
// С CORS
$app->add_route([
'url' => '/api/cross-origin',
'type' => ['get', 'post', 'options'],
'class_name' => \App\Routes\ApiRoute::class,
'method' => 'handle',
'cors' => [
'allow_origin' => ['https://example.com'],
'allow_methods' => ['GET', 'POST', 'OPTIONS'],
'allow_headers' => ['Content-Type', 'Authorization'],
],
]);
Класс маршрута
Наследуйтесь от IO\Route:
namespace App\Routes;
use IO\Route;
use IO\Response;
class UserRoute extends Route
{
public function index(): \IO\Response
{
$users = \IO\Core::callAction('app.model.user.search', []);
return $this->json($users);
}
public function show(): \IO\Response
{
$id = $this->args['id'];
$user = \IO\Core::callAction('app.model.user.getByID', ['pkid' => $id]);
return $this->json($user);
}
public function create(): \IO\Response
{
$data = $this->request->input();
$result = \IO\Core::callAction('app.model.user.create', [
'item' => $data,
]);
return $this->json($result, 201);
}
}
Методы Route для ответов
| Метод | Возвращает | Описание |
|---|---|---|
json(array, int) | Response | JSON-ответ |
text(string, int) | Response | Текстовый ответ |
render(string, array, int) | Response | Twig-шаблон |
redirect(string, int) | Response | Редирект |
noContent(int) | Response | Пустой ответ |
handleResponse(mixed) | Response | Авто-определение типа |
// JSON
return $this->json(['data' => $items]);
// Twig шаблон
return $this->render('@app/pages/users.twig', [
'users' => $users,
'title' => 'Пользователи',
]);
// Редирект
return $this->redirect('/login');
// Автоматическое определение
return $this->handleResponse(['status' => 'ok']); // → JSON
return $this->handleResponse('Hello'); // → text
return $this->handleResponse(null); // → 204
Доступ к данным
// Параметры URL (/users/:id)
$id = $this->args['id'];
// Запрос
$this->request->input('name'); // любой параметр
$this->request->query('page'); // GET параметр
$this->request->post('email'); // POST параметр
$this->request->route('id'); // параметр маршрута
$this->request->json('data'); // JSON тело
$this->request->all(); // все параметры
$this->request->only(['name', 'email']); // только указанные
$this->request->except(['password']); // кроме указанных
$this->request->hasFile('avatar'); // проверка файла
// Контекст middleware
$this->get('user_id');
$this->set('data', $value);
$this->has('key');
Регистрация через модули
class Module extends \IO\Module
{
public static function init(\IO\App $app): void
{
$app->add_routes([
\App\Routes\Web::class,
\App\Routes\Api::class,
]);
}
}