M4W Framework
Khởi tạo ứng dụng
composer create-project mini4work/framework my-app
cd my-app
composer require mini4work/webserverService của ứng dụng
Lưu lớp này vào app/Services/RequestInfo.php. Constructor yêu cầu container của framework cung cấp request hiện tại.
<?php
namespace App\Services;
use M4W\WebServer\Http\Request;
final class RequestInfo
{
public function __construct(private Request $request) {}
public function describe(): array
{
return ['method' => $this->request->method, 'uri' => $this->request->uri];
}
}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 m4w. Mỗi request có container riêng. Đăng ký request trước khi lấy service từ container.
<?php
use App\Services\RequestInfo;
use M4W\Core\Framework;
use M4W\WebServer\Cli\ServerCommand;
use M4W\WebServer\Http\CallbackRequestHandler;
use M4W\WebServer\Http\Request;
use M4W\WebServer\Http\Response;
require __DIR__.'/vendor/autoload.php';
$handler = new CallbackRequestHandler(static function (Request $request): Response {
$app = new Framework();
$app->singleton(Request::class, $request);
return Response::json($app->make(RequestInfo::class)->describe());
});
exit((new ServerCommand)->run($argv, $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 }
}php server.php m4w.jsonTrong một terminal khác, gửi một yêu cầu đến listener loopback.
curl -i 'http://127.0.0.1:9000/inspect?q=hello'{"method": "GET", "uri": "/inspect?q=hello"}