schnittstabil/psr7-middleware-stack

Stack PSR-7 middlewares in a reusable way.

3.0.1 2016-04-08 15:21 UTC

This package is auto-updated.

Last update: 2021-09-25 19:49:12 UTC


README

SensioLabsInsight

Stack PSR-7 middlewares in a reusable way 🍡

Install

$ composer require schnittstabil/psr7-middleware-stack

Usage

<?php
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Schnittstabil\Psr7\MiddlewareStack\MiddlewareStack;

$newMiddleware = (new MiddlewareStack())
  ->add($someMiddleware4)
  ->add($someMiddleware3)
  ->add(
    function (RequestInterface $req, ResponseInterface $res, callable $next) {
      $res->getBody()->write('Greetings from the the 2nd middleware.');
      return $next($req, $res);
    }
  )
  ->add($someMiddleware1);
?>

Slim Example

Suppose we want to minify the response of some, but not all routes by Oscar Otero's psr7-middlewares in a reusable way.

Install dependencies:

$ composer require slim/slim
$ composer require oscarotero/psr7-middlewares
$ composer require mrclay/minify
$ composer require willdurand/negotiation

app.php

<?php
require __DIR__.'/vendor/autoload.php';

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr7Middlewares\Middleware;
use Slim\App;
use Slim\Http\Stream;
use Schnittstabil\Psr7\MiddlewareStack\MiddlewareStack;

// setup oscarotero/psr7-middlewares
Middleware::setStreamFactory(function ($file, $mode) {
    return new Stream(fopen($file, $mode));
});

$app = new App();

$app->getContainer()['minifyMiddleware'] = function ($c) {
    return (new MiddlewareStack())
        ->add(Middleware::Minify())
        ->add(Middleware::FormatNegotiator());
};

$app->get('/', function (RequestInterface $request, ResponseInterface $response) {
    $body = '<!-- comment --><h1>Hello world!</h1><!-- comment -->';

    return $response->write($body);
})->add('minifyMiddleware');

$app->run();
?>

License

MIT © Michael Mayer