PSR-15 middleware dispatcher
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
LICENSE
README.md
composer.json

README.md

PSR-15 middleware dispatcher

codeinc/middleware-dispatcher is a PSR-15 middleware dispatcher. The middleware dispatcher behaves as a PSR-15 RequestHandlerInterface. It comes in two forms, an abstract class AbstractMiddlewareDispatcher to be extended and a final class MiddlewareDispatcher.

If none of middleware added to the dispatcher can process the request, a final request handler is called. By default this request handler is DefaultFinalRequestHandler which returns a NotFoundResponse.

Usage

<?php
use CodeInc\MiddlewareDispatcher\MiddlewareDispatcher;

// instantiating the dispatcher
$dispatcher = new MiddlewareDispatcher([
    new MyFirstMiddleware(),
    new MySecondMiddleware()
]);
$dispatcher->addMiddleware(new MyThirdMiddleware());

// handling the request 
// will return a NoResponseAvailable object if the request can not be processed by the middleware
// --> $psr7ServerRequest must be an object implementing ServerRequestInterface
$psr7Response = $dispatcher->handle($psr7ServerRequest); 

An alternative dispatcher called MiddlewareIteratorDispatcher allows to use an iterator as source for the dispatcher. Below is an example using a generator. In this example, the middleware objects are instantiated on the fly. This avoids instantiating unsued middleware objects. If the first middleware is capable of generating a valid response, the next ones will never be instantiated.

<?php
use CodeInc\MiddlewareDispatcher\MiddlewareIteratorDispatcher;

$dispatcher = new MiddlewareIteratorDispatcher(function():Generator {
    yield new MyFirstMiddleware();
    yield new MySecondMiddleware();
    yield new MyThirdMiddleware();
});
$psr7Response = $dispatcher->handle($psr7ServerRequest); 

Installation

This library is available through Packagist and can be installed using Composer:

composer require codeinc/middleware-dispatcher

License

This library is published under the MIT license (see the LICENSE file).