odan / middleware
Symfony HTTP Foundation middleware
Installs: 363
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
Type:project
Requires
- php: ^5.6 || ^7.0
- monolog/monolog: ^1.18.0
- symfony/http-foundation: ^3.2
- symfony/routing: ^3.2
Requires (Dev)
- phpunit/phpunit: 5.7
This package is not auto-updated.
Last update: 2017-11-19 12:23:14 UTC
README
Symfony HTTP Foundation middleware.
Features
Symfony middleware
- ExceptionMiddleware - Exception handling and logging (PSR-3)
- JsonMiddleware - Json request and response handling
- RouterMiddleware - Routing and dispatching
- SessionMiddleware - Session handling
Installation
composer install odan/middleware
Symfony HttpFoundation Middlware
The structure of a typical symfony middleware is almost identical with a PSR-7 middleware. The only difference is the symfony request and response object (see the namespace).
A symfony middleware must have the following signature:
function ( Request $request, // the request Response $response, // the response callable $next // the next callback ) { // ... }
Middleware (Example)
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class MyMiddleware { /** * Middleware. * * @param Request $request The request. * @param Response $response The response. * @param callable $next Callback to invoke the next middleware. * @return Response A response */ public function __invoke(Request $request, Response $response, callable $next) { // do some fance stuff $response->setContent('Hello Middleware World!'); // Call next calback and return response object return $next($request, $response); } }
Next, we need a middleware Dispachers which will run our callback functions.
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Middleware dispatcher. * * @param Request $request Request objct * @param Response $response Response object * @param array $queue Array with middleware * @return Response response */ function relay(Request $request, Response $response, array $queue) { $runner = function (Request $request, Response $response) use(&$queue, &$runner) { $middleware = array_shift($queue); if ($middleware) { return $middleware($request, $response, $runner); } return $response; }; return $runner($request, $response); }
In a queue, we define a list of middleware callables.
// Create a queue array of middleware callables $queue = []; $queue[] = new MyMiddleware(); // add more...
Finally, we run the queue through the middleware-runner and send the response.
$request = Request::createFromGlobals(); $response = new Response('', 200); $sprinter = new \Odan\Middleware\Dispatcher\HttpFoundationSprinter(); $response = $sprinter->run($request, $response, $queue); $response->send();
Configuration
todo
Usage
todo