A PSR-15 handler with no assumption
Pipe is licensed under the MIT license.
$ composer require gamringer/pipe
$ composer install
$ phpunit
These are all the various ways in which Pipe can be used. These examples can be found in the examples directory. First, let the following code simply be assumed present in all examples:
<?php
declare(strict_types=1);
include __DIR__.'/../vendor/autoload.php';
use GuzzleHttp\Psr7\ServerRequest;
use GuzzleHttp\Psr7\Response;
use gamringer\Pipe\Pipe;
use gamringer\Pipe\Example\StaticMiddleware;
// Request to be handled later
$request = new ServerRequest('GET', '/');
// For use in this example, we build a few Middleware objects
// One that simply returns a predetermined response in all cases
$staticResponse = new Response();
$staticResponseMiddleware = new StaticMiddleware($staticResponse);
// One that echoes it's constructor argument before passing to the next one.
$fooMiddleware = new FooMiddleware('1');
// Build Pipe from an array of Middlewares
$pipe = new Pipe([
$staticResponseMiddleware,
]);
// Use Pipe via RequestHandlerInterface
$response = $pipe->handle($request);
// Build empty Pipe
$pipe = new Pipe();
// Add Middlewares dynamically
$pipe->push($staticResponseMiddleware);
// Use Pipe via RequestHandlerInterface
$response = $pipe->handle($request);
// Build empty Pipe
$pipe = new Pipe();
// Add Middlewares dynamically
$pipe->push($fooMiddleware);
$pipe->push($staticResponseMiddleware);
// Use Pipe via RequestHandlerInterface
$response = $pipe->handle($request);
Pipe can also be used via the MiddlewareInterface by pushing it into another Pipe
// Build empty Pipe
$pipe = new Pipe();
// Add Middlewares dynamically
$pipe->push($fooMiddleware);
$pipe->push(new Pipe([
new FooMiddleware('2')
]));
$pipe->push($staticResponseMiddleware);
// Use Pipe via RequestHandlerInterface
$response = $pipe->handle($request);
If it runs out of middlewares to call, Pipe will respond differently depending on the way it was called.
Most applications will be using Pipe as a RequestHandler to stack Middlewares and handle user requests. If the request goes through the Pipe and the last Middleware attempts to delegate to the next one, a TerminalException is raised. The same logic also covers the empty Pipe case:
$pipe = new Pipe();
$pipe->handle($request); // Throws new \gamringer\Pipe\TerminalException()
If called as a Middleware, when running out of Middlewares itself, it will simply pass along to its next sibling:
// Build empty Pipe
$pipe = new Pipe();
// Add Middlewares dynamically
$pipe->push($fooMiddleware);
$pipe->push(new Pipe([
new FooMiddleware('2')
]));
$pipe->push(new Pipe());
$pipe->push($staticResponseMiddleware);
// Use Pipe via RequestHandlerInterface
$response = $pipe->handle($request);