Skip to content

schnittstabil/psr7-middleware-stack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Psr7\MiddlewareStack Build Status Coverage Status Scrutinizer Code Quality Code Climate

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

About

Stack PSR-7 middlewares in a reusable way 🍡

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages