middlewares/fast-route

Middleware to use FastRoute

Package info

github.com/middlewares/fast-route

pkg:composer/middlewares/fast-route

Statistics

Installs: 203 412

Dependents: 16

Suggesters: 0

Stars: 96

Open Issues: 0

v2.1.0 2025-03-23 10:31 UTC

Requires

Suggests

None

Provides

None

Conflicts

None

Replaces

None

MIT b9c587571b396efc0278ec2be490e78e595b06fa

httprouterservermiddlewareFastRoutepsr-7fast-routepsr-15

This package is auto-updated.

Last update: 2026-05-26 17:28:32 UTC


README

👁 Latest Version on Packagist
👁 Software License
👁 Testing
👁 Total Downloads

Middleware to use FastRoute for handler discovery.

Requirements

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.