kuick / routing
Routing package implementing PSR-15 middleware interface
v1.2.2
2026-05-12 22:17 UTC
Requires
- php: >=8.2.0
- kuick/http: ^1.0|^2.0
- psr/log: ^3.0
Requires (Dev)
- kuick/qa-toolkit: ^2.0
Provides
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.