codeinc/middleware-dispatcher

This package is abandoned and no longer maintained. No replacement package was suggested.

Code Inc. PSR15 middleware dispatcher

2.2.0 2018-10-11 17:29 UTC

This package is auto-updated.

Last update: 2020-02-11 20:07:24 UTC


README

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