Middleware to use FastRoute for handler discovery

Last update: Apr 27, 2022

middlewares/fast-route

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.

attribute('route'), //Execute the route handler (new Middlewares\RequestHandler())->handlerAttribute('route') ]);">
$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.

GitHub

https://github.com/middlewares/fast-route
Comments
  • 1. feat: continueOnNotFound option

    Hi,

    What do you think about this? I have a use case where I need to have a New Router on top of an Old Router, so if the New Router does not find a route for the Request, it gives the opportunity to the Old Router to handle it and try to match a route for it.

    To give a bit more context, in the Old Router I check whether the request-handler attribute is already set in which case I delegate to the next handler:

    if ($request->getAttribute('request-handler') !== null) {
        return $next->handle($request);
    }
    

    I think we should handle these situations where we might have "multiple request handlers finders" (routers).

    I'm also thinking about whether It would be a good idea to have some sort of "404 not found" behaviour (set default 404 Response) for the request-handler component if the request-handler attribute was not set in any of the handlers.

    Let me know what you think and if it's ok I can update the README.md and do the same for the Aura Router package.


    P.D: Now I also have doubts about what should happen with the 405.

    Reviewed by filisko at 2021-05-02 21:01
  • 2. Add ResponseFactoryInterface param to construct.

    Like a Dispatcher instance, a ResponseFactoryInterface instance must be available for this middleware to run. It makes sense for it to be set during construction.

    This also enables automatic dependency injecting (“autowiring”) such as available through Auryn, PHP-DI, Symfony, and (probably) many others.

    Another perk is that Factory::getResponseFactory gets to run during construction now as well. If it is incapable of finding a factory it can throw there, rather than waiting for FastRoute::process to be called.

    I have left the FastRoute::responseFactory method in case people want to change their response factory after the fact. But am tempted to remove it. There isn’t a separate method for changing the dispatcher after construction either.

    What do you think?

    I’d also appreciate some guidance on how you’d like this documented in the README in case you would consider merging 😃

    Reviewed by Zegnat at 2018-08-02 14:34
  • 3. Support array callables with resolver

    Currently if the callable is an array the resolver will be called with this array as the id.

    Callable arrays with fast route usually look like this:

    [\Namespace\To\Controller::class, 'methodName']

    I propose adding an extra check and only try to resolve the first element of the array here

    WDYT?

    Reviewed by sagikazarmark at 2017-02-04 20:29
  • 4. Deprecated: Non-static method should not be called statically in...

    How can I make working for example this route? ['GET', '/article/{id}', ['SuperBlog\Controller\ArticleController', 'show']] ?

    It works with FastRoute but in middle ore I get this error:

    Deprecated: Non-static method SuperBlog\Controller\ArticleController::show() should not be called statically in.

    ArticleController constructor has 3 params and I am using php-di and Relay packages.

    Reviewed by piticu14 at 2018-10-25 14:07
  • 5. Allow to access the matched route in the request or response

    I could not find a way to access the matched route pattern for a given request or its consequent response. Being able to access to it would be good for observability purposes.

    Reviewed by jcchavezs at 2020-06-24 19:52
  • 6. Split middleware into discovery and action

    By separating discovery from resolving and invoking, it is possible to apply routing earlier in the middleware process to handle 404s and 405s as quickly as possible, before doing any additional work in other middleware.

    This provides a clearer separation of concerns and allows more complex use cases.

    Reviewed by shadowhand at 2017-04-19 14:16
  • 7. Add support for injecting a callable resolver

    Right now the only option for people that do not use PSR-11 containers is to make all of their routes into closures. By allowing direct injection of a callable resolver, anyone will be able to write a resolver that suites their application.

    This breaks backwards compatibility by replacing the previous resolver and moving it to container().

    Reviewed by shadowhand at 2017-04-13 18:06
  • 8. 404 and 405

    Are there any code examples of how to implement the 404 and 405 custom errors? Also are there any examples are how to implement things like 301 redirect responses in connection with the return?

    Reviewed by mav2287 at 2020-10-15 22:10
  • 9. composer: allow php ^8.0

    closes https://github.com/middlewares/fast-route/issues/14

    Should I send also migration from Travis to GitHub actions? Since Travis is ultra-slow these days and obviously does not have PHP 8.0 ready, GitHub actions are far better nowadays.

    I pushed the example of GitHub actions in this repository. If you want, I can prepare the same for the others.

    You can look into https://github.com/solcik/fast-route/actions/runs/388555467

    This one is ready .)

    • github actions
    • dependencies fixed
    • phpunit updated
    • phpstan added
    Reviewed by solcik at 2020-11-27 11:49
  • 10. Add support for encoded path

    Decode url path before matching routes to work with any path with accent.

    Example

    • http://localhost:8080/hello/accentu%C3%A9

    Which should decoded as:

    • http://localhost:8080/hello/accentué

    This is also done in Symfony: https://github.com/symfony/symfony/blob/4.2/src/Symfony/Component/Routing/Matcher/UrlMatcher.php#L87

    Reviewed by smalot at 2019-03-31 22:24
  • 11. Only request handler discovery

    This removes all handler/controller resolving and invoking. By separating discovery from execution, it is possible to apply routing much earlier and send 404s and 405s as soon as possible.

    This provides clearer separation of concerns and allows more complex middleware configurations.

    Refs #5

    Reviewed by shadowhand at 2017-04-19 16:17
Auto Route Generating (Auto-Discovery) Package for Laravel.

Laravel Auto Routes _ _____ _ /\ | | | __ \ | |

May 16, 2022
Fast PSR-7 based routing and dispatch component including PSR-15 middleware, built on top of FastRoute.

Route This package is compliant with PSR-1, PSR-2, PSR-4, PSR-7, PSR-11 and PSR-15. If you notice compliance oversights, please send a patch via pull

May 24, 2022
A super simple, clean and pretty error handler that replace the default error handler of PHP. You need only include this file!

php-custom-error-handler A super simple, clean and pretty error handler that replace the default error handler of PHP. You need just include only this

Mar 30, 2022
PSR-15 middleware to use Whoops as error handler

middlewares/whoops Middleware to use Whoops as error handler. Requirements PHP >= 7.2 A PSR-7 http library A PSR-15 middleware dispatcher Installation

May 3, 2022
Juliangut Slim Framework Doctrine handler middleware

Juliangut Slim Framework Doctrine handler middleware Doctrine handler middleware for Slim Framework. Slim3 version Doctrine integration service for Sl

Mar 23, 2021
Auto Route Generating (Auto-Discovery) Package for Laravel.

Laravel Auto Routes _ _____ _ /\ | | | __ \ | |

May 16, 2022
A PHP client for (Spring Cloud) Netflix Eureka service registration and discovery.

PHP Netflix Eureka Client A PHP client for (Spring Cloud) Netflix Eureka service registration and discovery. Installation You can install this package

Apr 6, 2022
Dictionary of attack patterns and primitives for black-box application fault injection and resource discovery.

FuzzDB was created to increase the likelihood of finding application security vulnerabilities through dynamic application security testing. It's the f

May 20, 2022
CollectiveAccess is a web-based suite of applications providing a framework for management, description, and discovery of complex digital

README: Pawtucket2 version 1.7.14 About CollectiveAccess CollectiveAccess is a web-based suite of applications providing a framework for management, d

Mar 31, 2022
PSR-7 middleware foundation for building and dispatching middleware pipelines

laminas-stratigility From "Strata", Latin for "layer", and "agility". This package supersedes and replaces phly/conduit. Stratigility is a port of Sen

May 1, 2022
Bounce Mail Handler for PHP | This is a "reboot" of PHPMailer-BMH from WorxWare.

PHP 7.0+ Support Composer & PSR-0 Support PHPUnit testing via Travis CI (TODO: more tests needed) PHP-Quality testing via SensioLabsInsight (TODO: mor

Mar 25, 2022
Amazon Web Services CloudWatch Logs Handler for Monolog library

AWS CloudWatch Logs Handler for Monolog Handler for PHP logging library Monolog for sending log entries to AWS CloudWatch Logs service. Before using t

May 24, 2022
A PSR-15 server request handler.

Relay A PSR-15 request handler. This package is installable and PSR-4 autoloadable via Composer as "relay/relay": "~2.0". Alternatively, download a re

May 6, 2022
An alternative Redis session handler for PHP featuring per-session locking and session fixation protection

RedisSessionHandler An alternative Redis session handler featuring session locking and session fixation protection. News phpredis v4.1.0 (released on

May 5, 2022
Simple handler system used to power clients and servers in PHP (this project is no longer used in Guzzle 6+)

RingPHP Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function. RingPHP be used to power HTTP clie

May 19, 2022
It's authorization form, login button handler and login to your personal account, logout button
It's authorization form, login button handler and login to your personal account, logout button

Authorization-form It's authorization form, login button handler and login to your personal account, logout button Each file is: header.php - html-fil

Nov 2, 2021
Yii Caching Library - Redis Handler
 Yii Caching Library - Redis Handler

Yii Caching Library - Redis Handler This package provides the Redis handler and implements PSR-16 cache. Requirements PHP 7.4 or higher. Installation

Jan 10, 2022
Server-side handler of DataTables Jquery Plugin for Laravel 4

Project is not being maintained actively. You will most likely find a better more actively maintained fork here https://github.com/yajra/laravel-datat

May 3, 2022
AWS DynamoDB session handler for Magento (experimental!)

Magento Session Handler for AWS DynamoDB Author: Fabrizio Branca TODO: disable automatic gc create cron that does gc how does it keep track of lifetim

Apr 6, 2017
Redis-based session handler for Magento with optimistic locking

Cm_RedisSession A Redis-based session handler for Magento with optimistic locking. Features: Falls back to mysql handler if it can't connect to Redis.

May 17, 2022