Slim 4
Chạy route Slim qua adapter PSR-15. Slim đọc tên từ cookie của request và ghi lời chào vào response PSR-7.
Cài đặt gói
composer require 'mini4work/webserver:^1.8' 'slim/slim:^4' '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 Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Factory\AppFactory;
require __DIR__.'/vendor/autoload.php';
$app = AppFactory::create(new Psr17Factory);
$app->post('/hello', static function (ServerRequestInterface $request, ResponseInterface $response) {
$name = $request->getCookieParams()['name'] ?? null;
$response->getBody()->write('Hello '.(is_string($name) ? $name : 'guest'));
return $response;
});
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