kuick/routing
最新稳定版本:v1.2.2
Composer 安装命令:
composer require kuick/routing
包简介
Routing package implementing PSR-15 middleware interface
README 文档
README
Routing package implementing PSR-15 middleware
Key features
- PSR-15(https://www.php-fig.org/psr/psr-15/) routing middleware implementation
- Support for flexible Routes (any callable)
- Router service for matching Routes to the Request
- Routes supporting regex paths with named parameters
Installation
composer require kuick/routing
Usage
1. Define controllers
Controllers are any callable (closure, invokable class, etc.) that accept a ServerRequestInterface and return a ResponseInterface:
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; $helloController = function (ServerRequestInterface $request): ResponseInterface { $name = $request->getQueryParams()['name'] ?? 'World'; return new \Kuick\Http\Message\Response(200, [], "Hello, $name!"); }; // Invokable class example class GetUserAction { public function __invoke(ServerRequestInterface $request): ResponseInterface { $id = $request->getQueryParams()['id']; return new \Kuick\Http\Message\Response(200, [], "User: $id"); } }
2. Set up the Router
Use Router::addRoute(path, controller, methods) to register routes. The path supports regex with named capture groups for dynamic segments:
use Kuick\Routing\Router; use Psr\Log\NullLogger; $router = (new Router(new NullLogger())) ->addRoute('/', $helloController, ['GET']) ->addRoute('/users/(?P<id>\d+)', new GetUserAction(), ['GET']) ->addRoute('/articles', $listArticlesController, ['GET', 'POST']);
Named regex groups (e.g. (?P<id>\d+)) are merged into the request's query params and accessible via $request->getQueryParams()['id'].
3. Use as a PSR-15 middleware
Wire RoutingMiddleware into your middleware pipeline. When a route matches, the controller is invoked and its response returned; otherwise the next handler in the chain is called:
use Kuick\Routing\Router; use Kuick\Routing\RoutingMiddleware; use Psr\Log\NullLogger; $router = (new Router(new NullLogger())) ->addRoute('/users/(?P<id>\d+)', new GetUserAction(), ['GET']); $middleware = new RoutingMiddleware($router, new NullLogger()); // $handler is the next PSR-15 RequestHandlerInterface in the pipeline $response = $middleware->process($request, $handler);
Notes
- Route paths are matched as full regex anchors (
^pattern$), so no partial matches occur. - A trailing
/is stripped from the request path before matching (except for the root/). HEADis automatically supported for any route that acceptsGET.- When no route matches, the request is forwarded to the next
RequestHandlerInterface.
统计信息
- 总下载量: 5.3k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 4
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-01-22