Stack PSR-7 middlewares in a reusable way 🍡
$ composer require schnittstabil/psr7-middleware-stack
<?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);
?>
Suppose we want to minify the response of some, but not all routes by Oscar Otero's psr7-middlewares in a reusable way.
$ composer require slim/slim
$ composer require oscarotero/psr7-middlewares
$ composer require mrclay/minify
$ composer require willdurand/negotiation
<?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();
?>
MIT © Michael Mayer