Mezzio 3

Bắt đầu với skeleton Mezzio đã cấu hình router. Ví dụ nạp container và chạy routing trước khi dispatch. Trong ứng dụng hiện có, chỉ nạp pipeline và các route một lần.

Cài đặt gói

Shell
composer require 'mini4work/webserver:^1.8' 'nyholm/psr7:^1.8'

Cấu trúc bộ xử lý yêu cầu

Lưu mã này vào server.php trong cùng thư mục với vendor/.

PHP
<?php

declare(strict_types=1);

use M4W\WebServer\Adapters\Psr\PsrRequestHandler;
use M4W\WebServer\Cli\ServerCommand;
use Mezzio\Application;
use Mezzio\Router\Middleware\DispatchMiddleware;
use Mezzio\Router\Middleware\RouteMiddleware;
use Nyholm\Psr7\Response;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;

require __DIR__.'/vendor/autoload.php';

/** @var ContainerInterface $container */
$container = require __DIR__.'/config/container.php';
/** @var Application $app */
$app = $container->get(Application::class);
$app->pipe(RouteMiddleware::class);
$app->pipe(DispatchMiddleware::class);
$app->post('/hello', static function (ServerRequestInterface $request) {
    $name = $request->getCookieParams()['name'] ?? null;

    return new Response(body: 'Hello '.(is_string($name) ? $name : 'guest'));
});

exit((new ServerCommand)->run($argv ?? [__FILE__], new PsrRequestHandler($app)));

Khởi động máy chủ

Lưu mã này vào m4w.json trong cùng thư mục với server.php.

JSON
{
  "listen": { "port": 9000 },
  "protocols": { "http": "1.1" },
  "tls": { "mode": "off" },
  "workers": { "count": 1 }
}
Shell
php server.php m4w.json

Gửi yêu cầu từ một terminal khác

Shell
curl -i -X POST --cookie 'name=Ada' http://127.0.0.1:9000/hello

HTTP/1.1 200 OK · Hello Ada