PHP code example of idealo / php-middleware-stack

1. Go to this page and download the library: Download idealo/php-middleware-stack library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

idealo / php-middleware-stack example snippets


use Idealo\Middleware\Stack;

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

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

// 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
bash 
composer