Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Создание своего HTTP обработчика.

Создание HTTP обработчиков это одна из основных задач разработчика API.

пример обработчика который обработает GET /example и выведет json {"message": "this is example}.

src/Example.php - расположить можно где угодно, главное следовать psr4.

declare(strict_types=1);

namespace App;

use Cekta\Framework\HTTP\Response\JSONFactory;
use Cekta\Framework\HTTP\Route;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

#[Route\GET('/example')]
final readonly class Welcome implements RequestHandlerInterface
{
    public function __construct(
        private JSONFactory $factory
    ) {
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return $this->factory->create(['message' => 'this is example']);
    }
}

CLI: нужно сделать build или полный перезапуск

make restart

Проверяем успешный результат открываем GET http://localhost:8080/example.

Зависимости внедрять через autowiring в конструктор, они будут подгружаться автоматически, необходимые параметры будут запрошены во время build.

Алгоритм в общем виде.

  1. Создайте класс (в любом месте) реализующий \Psr\Http\Server\RequestHandlerInterface
  2. Используйте php attribute \Cekta\Framework\HTTP\Route:
    1. pattern - url который должен обрабатываться
    2. method - http method (GET, POST, PATCH, …) есть alias где его задавать не нужно \Cekta\Framework\HTTP\Route\POST, \Cekta\Framework\HTTP\Route\DELETE и тд.
      По умолчанию: GET.
    3. middlewares - имена psr/middleware реализаций которые необходимо вызывать.
      По умолчанию: [].
  3. Сделайте build проекта или restart
    make restart
    
  4. Можно открывать endpoint с указанным method и pattern.