idealo/php-middleware-stack

Implementation of HTTP Middleware PSR-15 specification

v3.0.0 2024-10-21 14:15 UTC

This package is auto-updated.

Last update: 2024-11-21 14:32:42 UTC


README

Build Status Maintainability Test Coverage Packagist

This is an implementation of PSR-15 using the proposed Interface packages psr/http-server-middleware and psr/http-server-handler for PHP ^8.1 runtime environment.

It enables a sequential execution of middlewares that use a PSR-7 conform Response/Request implementation.

Install

composer require idealo/php-middleware-stack

Note: use Version ^2.0 for PHP < 8.1

How to

use Idealo\Middleware\Stack;

$stack = new Stack(
    $defaultResponse,
    $middleware1,
    $middleware2,
    $middleware3
);

$stackResponse = $stack->handle($request);

Usage

idealo/php-middleware-stack provides the Idealo\Middleware\Stack class. All it has to know in order to be instantiable is:

  • an instance of Psr\Http\Message\ResponseInterface as the default response
  • and middlewares, that implement the Psr\Http\Server\MiddlewareInterface

To perform a sequential processing of injected middlewares you have to call stack's handle method with:

  • an instance of Psr\Http\Message\ServerRequestInterface.

By default stack's handle method returns the injected response object. If any middleware decides to answer on it's own, than the response object of this certain middleware is returned.

Stack implements Psr\Http\Server\RequestHandlerInterface.

For example

// you decide what middleware you want to put in a stack.
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;

class TrickyMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
    {
        $requestBody = $request->getBody();
        try {
            // implement your middleware logic here  
        } catch (\Exception $exception){
            return new CustomExceptionResponse($exception);
        }
    
        return $handler->handle($request);
    }
}

class VeryTrickyMiddleware implements MiddlewareInterface
{
    ...
}

class LessTrickyMiddleware implements MiddlewareInterface
{
    ...
}

// you define your PSR7 conform response instance
$defaultResponse = new DefaultResponse();

// you put your request into a PSR7 conform way
$request = new ServerRequest();

// and here we are
$stack = new \Idealo\Middleware\Stack(
    $defaultResponse,
    new TrickyMiddleware(),
    new VeryTrickyMiddleware(),
    new LessTrickyMiddleware()
);

$stackResponse = $stack->handle($request);

// if everything goes well then
var_dump($stackResponse === $defaultResponse); // gives: true