kapitanluffy/middlewarestack

Implementing PSR-15 Middlewares in a single class

dev-master 2017-10-29 04:31 UTC

This package is auto-updated.

Last update: 2022-01-06 18:01:05 UTC


README

Implementing PSR-15 Middlewares in a single class.

Why?

As defined in the proposal, middlewares "processes" a request and returns a response. Similarly, RequestHandlers "handles" a request and returns a response. The idea of this package is to simplify the goals of the interfaces provided by PSR-15.

Install
composer require kapitanluffy/middlewarestack
Usage
use kapitanluffy\middleware\MiddlewareStack;
use Zend\Diactoros\ServerRequestFactory;

$innerStack = new MiddlewareStack(array(
    new Middlewares\Robots(false),
    new Middlewares\TrailingSlash(false)
));

$stack = new MiddlewareStack(array(
    new Middlewares\Whoops(),

    // Use another stack as middleware
    $innerStack,

    // Create an inner stack with arrays
    array(
        new Middlewares\ResponseTime(),
        new Middlewares\Uuid(),
    ),

    // Create closures as middlewares
    function ($request, $stack) {
        $response = $stack->handle($request);
        return $response->withHeader('X-Passed-MiddlewareClosure', 1);
    }
));

// let the middleware stack handle the request
$request = ServerRequestFactory::fromGlobals();
$response = $stack->handle($request);
Middlewares

You can find a list of middlewares here or implement your own by implementing the MiddlewareInterface