Быстрый старт
Соберём первый маршрут от начала до видимого результата: создадим проект, добавим контроллер, поднимем сервер и получим JSON-ответ. Займёт пять минут.
1. Проект
composer create-project flytachi/winter my-app
cd my-appПодробности и требования — на странице Установка.
2. Контроллер
Сгенерируем контроллер командой make (точка перед именем — обязательна;
суффикс Controller генератор добавит сам):
php call make -c .Greet # → main/GreetController.phpФайл main/GreetController.php появится и сразу подключится к автозагрузке.
Приведём его к такому виду — маршрут GET /api/hello/{name}, возвращающий JSON:
<?php
namespace Main;
use Flytachi\Winter\K2\Http\Request\Annotation\PathVariable;
use Flytachi\Winter\K2\Http\Response\ResponseEntity;
use Flytachi\Winter\K2\Route\Annotation\GetMapping;
use Flytachi\Winter\K2\Route\Annotation\RequestMapping;
use Flytachi\Winter\K2\Stereotype\Controller;
#[RequestMapping('api')]
class GreetController extends Controller
{
#[GetMapping('hello/{name}')]
public function hello(#[PathVariable] string $name): ResponseEntity
{
return ResponseEntity::ok(['message' => "Hello, {$name}"]);
}
}Что здесь происходит:
#[RequestMapping('api')]на классе — общий префикс/apiдля всех методов.#[GetMapping('hello/{name}')]— маршрутGET /api/hello/{name}.#[PathVariable]привязывает сегмент{name}к аргументу$name.ResponseEntity::ok([...])отдаёт200 OKс телом в JSON.
Регистрировать маршрут не нужно — сканер найдёт его сам.
3. Запуск
php call run devСервер поднимется на http://0.0.0.0:8000.
4. Результат
curl http://0.0.0.0:8000/api/hello/Winter{"message":"Hello, Winter"}Или откройте http://0.0.0.0:8000/api/hello/Winter в браузере — увидите тот же JSON.
Маршрут не найден?
В режиме разработки (DEBUG=true) маршруты сканируются на каждый запрос, так что
новый контроллер виден сразу. Список всех маршрутов — php call mapping show.
5. Чуть больше: query-параметр
Добавим необязательный параметр ?shout=true через #[RequestQuery]:
#[GetMapping('hello/{name}')]
public function hello(
#[PathVariable] string $name,
#[RequestQuery] bool $shout = false,
): ResponseEntity {
$message = "Hello, {$name}";
return ResponseEntity::ok(['message' => $shout ? strtoupper($message) : $message]);
}curl 'http://0.0.0.0:8000/api/hello/Winter?shout=true'{"message":"HELLO, WINTER"}Не забудьте импорт use Flytachi\\Winter\\K2\\Http\\Request\\Annotation\\RequestQuery;.
Весь код целиком
<?php
namespace Main;
use Flytachi\Winter\K2\Http\Request\Annotation\PathVariable;
use Flytachi\Winter\K2\Http\Request\Annotation\RequestQuery;
use Flytachi\Winter\K2\Http\Response\ResponseEntity;
use Flytachi\Winter\K2\Route\Annotation\GetMapping;
use Flytachi\Winter\K2\Route\Annotation\RequestMapping;
use Flytachi\Winter\K2\Stereotype\Controller;
#[RequestMapping('api')]
class GreetController extends Controller
{
#[GetMapping('hello/{name}')]
public function hello(
#[PathVariable] string $name,
#[RequestQuery] bool $shout = false,
): ResponseEntity {
$message = "Hello, {$name}";
return ResponseEntity::ok(['message' => $shout ? strtoupper($message) : $message]);
}
}Дальше
- Ключевые понятия — как всё связано
- Философия — почему именно так
- Экосистема — из чего собран фреймворк