diff --git a/README.md b/README.md index 716284e..d5a4038 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ and using the callback to call several methods on the redirect middleware to cha ```php $loop = Factory::create(); -$server = new Server(new MiddlewareRunner([ +$server = new Server([ /** Other middleware */ new PSR15Middleware( $loop, // The react/event-loop (required) @@ -36,7 +36,33 @@ $server = new Server(new MiddlewareRunner([ } ), /** Other middleware */ -])); +]); +``` + +# Grouped Usage + +When using more then one PSR-15 in a row the `GroupedPSR15Middleware` is more performing than using multiple `PSR15Middleware`. Consider the +following example where we add [`middlewares/cache`](https://github.com/middlewares/cache) for expires headers: + +```php +$loop = Factory::create(); +$server = new Server([ + /** Other middleware */ + (new GroupedPSR15Middleware($loop))->withMiddleware( + Redirect::class, + [ + ['/old-url' => '/new-url'] + ], + function ($redirectMiddleware) { + return $redirectMiddleware + ->permanent(false) + ->query(false) + ->method(['GET', 'POST']) + ; + } + )->withMiddleware(Expires::class), + /** Other middleware */ +]); ``` # Warning diff --git a/src/GroupedPSR15Middleware.php b/src/GroupedPSR15Middleware.php index 0210661..aec64b7 100644 --- a/src/GroupedPSR15Middleware.php +++ b/src/GroupedPSR15Middleware.php @@ -27,7 +27,7 @@ public function __construct(LoopInterface $loop) $this->kernel = ReactKernel::create($loop); } - public function add(string $middleware, array $arguments = [], callable $func = null) + public function withMiddleware(string $middleware, array $arguments = [], callable $func = null) { if ($func === null) { $func = function ($middleware) { @@ -35,9 +35,10 @@ public function add(string $middleware, array $arguments = [], callable $func = }; } - $this->middleware[] = $func(YieldingMiddlewareFactory::construct($middleware, $arguments)); + $clone = clone $this; + $clone->middleware[] = $func(YieldingMiddlewareFactory::construct($middleware, $arguments)); - return $this; + return $clone; } public function __invoke(ServerRequestInterface $request, callable $next): Promise\PromiseInterface