middlewares / fast-route
Middleware to use FastRoute
Installs: 166 776
Dependents: 16
Suggesters: 0
Security: 0
Stars: 95
Watchers: 5
Forks: 9
Open Issues: 0
Requires
- php: ^7.2 || ^8.0
- middlewares/utils: ^3.0
- nikic/fast-route: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.3
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8|^9
- squizlabs/php_codesniffer: ^3.0
README
Middleware to use FastRoute for handler discovery.
Requirements
- PHP >= 7.2
- A PSR-7 http library
- A PSR-15 middleware dispatcher
Installation
This package is installable and autoloadable via Composer as middlewares/fast-route.
composer require middlewares/fast-route
You may also want to install middlewares/request-handler.
Example
This example uses middlewares/request-handler to execute the route handler:
//Create the router dispatcher $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) { $r->addRoute('GET', '/hello/{name}', function ($request) { //The route parameters are stored as attributes $name = $request->getAttribute('name'); //You can echo the output (it will be captured and written into the body) echo sprintf('Hello %s', $name); //Or return a string return sprintf('Hello %s', $name); //Or return a response return new Response(); }); }); $dispatcher = new Dispatcher([ new Middlewares\FastRoute($dispatcher), new Middlewares\RequestHandler() ]); $response = $dispatcher->dispatch(new ServerRequest('/hello/world'));
FastRoute allows anything to be defined as the router handler (a closure, callback, action object, controller class, etc). The middleware will store this handler in a request attribute.
Usage
Create the middleware with a FastRoute\Dispatcher
instance:
$route = new Middlewares\FastRoute($dispatcher);
Optionally, you can provide a Psr\Http\Message\ResponseFactoryInterface
as the second argument, that will be used to create the error responses (404
or 405
). If it's not defined, Middleware\Utils\Factory will be used to detect it automatically.
$responseFactory = new MyOwnResponseFactory(); $route = new Middlewares\FastRoute($dispatcher, $responseFactory);
attribute
Changes the attribute name used to store the handler in the server request. The default name is request-handler
.
$dispatcher = new Dispatcher([ //Save the route handler in an attribute called "route" (new Middlewares\FastRoute($dispatcher))->attribute('route'), //Execute the route handler (new Middlewares\RequestHandler())->handlerAttribute('route') ]);
Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.
The MIT License (MIT). Please see LICENSE for more information.