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
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
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.
{
"listen": { "port": 9000 },
"protocols": { "http": "1.1" },
"tls": { "mode": "off" },
"workers": { "count": 1 }
}php server.php m4w.jsonGửi yêu cầu từ một terminal khác
curl -i -X POST --cookie 'name=Ada' http://127.0.0.1:9000/helloHTTP/1.1 200 OK · Hello Ada