Yii3
Mỗi worker chạy một ứng dụng Yii. Truyền factory tạo PSR container cung cấp Application và StateResetter. Yii khởi động khi nhận request đầu tiên.
Cài đặt gói
composer require 'mini4work/webserver:^1.8' 'yiisoft/yii-http:^1.1' 'yiisoft/di:^1.5' '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\Yii\YiiRequestHandler;
use M4W\WebServer\Cli\ServerCommand;
use Nyholm\Psr7\Response;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Yiisoft\Di\Container;
use Yiisoft\Di\ContainerConfig;
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
use Yiisoft\Middleware\Dispatcher\MiddlewareFactory;
use Yiisoft\Yii\Http\Application;
require __DIR__.'/vendor/autoload.php';
$handler = new YiiRequestHandler(static fn () => new Container(ContainerConfig::create()->withDefinitions([
Application::class => static function (ContainerInterface $container) {
$dispatcher = new MiddlewareDispatcher(new MiddlewareFactory($container));
return new Application($dispatcher->withMiddlewares([
static function (ServerRequestInterface $request) {
if ($request->getUri()->getPath() !== '/hello') {
return new Response(404);
}
$name = $request->getCookieParams()['name'] ?? null;
return new Response(body: 'Hello '.(is_string($name) ? $name : 'guest'));
},
]));
},
])));
exit((new ServerCommand)->run($argv ?? [__FILE__], $handler));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
Trạng thái yêu cầu
Yii dùng giới hạn body và tệp tải lên mặc định của adapter PSR. Response chậm giữ container Yii của worker cho đến khi body đóng.
Các request đồng thời chờ theo thứ tự đến. Worker nhận request kế tiếp sau khi đóng body, gọi afterEmit() và dùng StateResetter reset các service đã đăng ký. Hãy đăng ký callback để xóa trạng thái riêng của request. Dispatch lỗi mà chưa có response sẽ gọi afterEmit(null). Worker dừng bình thường sẽ gọi shutdown().
Đặt queueTimeout thành số giây hữu hạn lớn hơn 0 (mặc định 5). Hết hạn, Yii trả 503 nếu tầng truyền tải chưa hủy request. Các stream trên cùng kết nối HTTP/2 dùng chung worker. Hủy request đang chờ sẽ giải phóng vị trí. HTTP/3 phân phối tác vụ qua pool tiến trình ứng dụng.
new YiiRequestHandler($containerFactory, queueTimeout: 2.0);