Middleware to use FastRoute for handler discovery

Overview

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.

Comments
  • feat: continueOnNotFound option

    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.

    opened by filisko 8
  • Add ResponseFactoryInterface param to construct.

    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 😃

    opened by Zegnat 8
  • Support array callables with resolver

    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?

    opened by sagikazarmark 7
  • Deprecated: Non-static method should not be called statically in...

    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.

    opened by piticu14 6
  • Allow to access the matched route in the request or response

    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.

    question 
    opened by jcchavezs 5
  • Split middleware into discovery and action

    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.

    enhancement 
    opened by shadowhand 4
  • Add support for injecting a callable resolver

    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().

    opened by shadowhand 4
  • 404 and 405

    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?

    question 
    opened by mav2287 3
  • composer: allow php ^8.0

    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
    opened by solcik 2
  • Add support for encoded path

    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

    enhancement 
    opened by smalot 2
  • Only request handler discovery

    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

    enhancement 
    opened by shadowhand 2
Owner
Middlewares
PSR-15 HTTP Middlewares
Middlewares
Auto Route Generating (Auto-Discovery) Package for Laravel.

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

İzni Burak Demirtaş 201 Jan 1, 2023
PHPRouter is an easy-to-use, fast, and flexible PHP router package with express-style routing.

PHP-Router is a modern, fast, and adaptable composer package that provides express-style routing in PHP without a framework.

Ayodeji O. 4 Oct 20, 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

The League of Extraordinary Packages 608 Dec 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

Middlewares 31 Jun 23, 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

null 6 Nov 7, 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

Julián Gutiérrez 6 Mar 23, 2021
PSR-15 compatible middleware for Whoops, the pretty error handler

PSR-15 middleware for Whoops A PSR-15 compatible middleware for Whoops, the fantastic pretty error handler for PHP. Installation You can install the l

Franz Liedke 25 May 20, 2022
Auto Route Generating (Auto-Discovery) Package for Laravel.

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

İzni Burak Demirtaş 201 Jan 1, 2023
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

Hamid Mohayeji 72 Aug 21, 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

FuzzDB Project 7.1k Dec 27, 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

CollectiveAccess 70 Sep 28, 2022
This library extends the 'League OAuth2 Client' library to provide OpenID Connect Discovery support for supporting providers that expose a .well-known configuration endpoint.

OpenID Connect Discovery support for League - OAuth 2.0 Client This library extends the League OAuth2 Client library to provide OpenID Connect Discove

null 3 Jan 8, 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

Laminas Project 47 Dec 22, 2022
Use middleware to decorate method calls within your application code.

Laravel Middlewarize ?? Chain of Responsibility Design Pattern In Laravel Apps ?? You can use middlewares to decorate any method calls on any object.

Iman 99 Jan 1, 2023
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

Lars Moelleken 43 Jan 7, 2023
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

Maksym Leonov 377 Dec 16, 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

Relay 304 Dec 30, 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

Marcel Hernandez 117 Oct 19, 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

Guzzle 846 Dec 6, 2022
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

Galina 2 Nov 2, 2021