API-маршрутизация
API-маршруты объявляются в файле routes.php:
use App\Http\Api;
use App\Http\Request;
use App\Http\Response;
Api::any('/greeting', function (Request $request) {
return new Response\Result(['message' => 'Hello, the framework!'], 200);
});
При необходимости их можно вынести в отдельные файлы и подключить через include_file().
include_file('/routes/api.php');
Типы обработчиков маршрутов
Маршрут можно обработать замыканием, статическим методом контроллера или методом объекта.
1. Замыкание
Api::any('/greeting', function (Request $request) {
return new Response\Result(['message' => 'Hello, the framework!'], 200);
});
2. Статический метод контроллера
Api::any('/greeting', [App\Controllers\GreetingController::class, 'index']);
// или
Api::any('/greeting', 'App\Controllers\GreetingController::index');
Пример контроллера:
namespace App\Controllers;
use App\Base\Interfaces\Response as ApiResponse;
use App\Http\Request;
use App\Http\Response;
class GreetingController
{
public static function index(Request $request): ApiResponse
{
return new Response\Result(['message' => 'Hello, the framework!'], 200);
}
}
3. Метод объекта
Api::any('/greeting', [new App\Controllers\GreetingController(), 'index']);
Пример контроллера:
namespace App\Controllers;
use App\Base\Interfaces\Response as ApiResponse;
use App\Http\Request;
use App\Http\Response;
class GreetingController
{
public function index(Request $request): ApiResponse
{
return new Response\Result(['message' => 'Hello, the framework!'], 200);
}
}
HTTP-методы
Метод Api::any() регистрирует маршрут для всех HTTP-методов. При необходимости можно указать конкретный
метод.
Api::get($uri, $callback);
Api::post($uri, $callback);
Api::put($uri, $callback);
Api::patch($uri, $callback);
Api::delete($uri, $callback);
Если один маршрут должен отвечать на несколько методов, используйте Api::match().
Api::match(['get', 'post'], '/greeting', function (Request $request) {
return new Response\Result(['message' => 'Hello, the framework!'], 200);
});
Параметры маршрута
Параметры маршрута позволяют передавать данные через динамические сегменты URL. Параметры заключаются в фигурные
скобки {}.
Api::any('/user/{id}', function (Request $request, int $id) {
return new Response\Result(["User #$id"], 200);
});
При переходе по адресу http://localhost:8001/api/user/1 значение
$id будет равно 1, а ответ будет таким:
{
"result": [
"User #1"
]
}
Можно объявлять несколько параметров в одном маршруте:
Api::any('/posts/{postId}/comments/{commentId}', function (Request $request, int $postId, int $commentId) {
return new Response\Result([
"Post #$postId",
"Comment #$commentId"
], 200);
});