odan/middleware

This package is abandoned and no longer maintained. No replacement package was suggested.

Symfony HTTP Foundation middleware

dev-master 2017-06-08 21:26 UTC

This package is not auto-updated.

Last update: 2017-11-19 12:23:14 UTC


README

Symfony HTTP Foundation middleware.

Latest Version Build Status Crutinizer Code Coverage Total Downloads Software License

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