diff --git a/source/_views/default.html b/source/_views/default.html index f1977ef..0b1d849 100644 --- a/source/_views/default.html +++ b/source/_views/default.html @@ -21,12 +21,12 @@
Creating a new middleware is generally quite easy. The hardest part is grasping the decorator pattern.
+A decorator is simply an object that wraps around an other object. In this case a middleware is a decorator for HttpKernelInterface
. The decorator wraps around a kernel, and exposes the same interface.
Let's take a look at an PoweredByStack
middleware, that adds a `X-Powered-By` header to all responses.
{%- filter escape -%}use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpKernel\HttpKernelInterface;
+
+class PoweredByStack implements HttpKernelInterface
+{
+ private $app;
+
+ public function __construct(HttpKernelInterface $app)
+ {
+ $this->app = $app;
+ }
+
+ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
+ {
+ $response = $this->app->handle($request, $type, $catch);
+ $response->headers->set('X-Powered-By', 'Stack');
+ return $response;
+ }
+}{%- endfilter -%}
+ This middleware takes a kernel in the constructor and delegates to this kernel from within handle
. Then it augments the response. It decorates the handle
call.
Here is an example of how you could use this middleware with Silex. Note that you can replace Silex with any kernel implementation.
+{%- filter escape -%}$app = new Silex\Application();
+
+$app->get('/', function () {
+ return 'Hello World!';
+});
+
+$app = new PoweredByStack($app);
+
+Stack\run($app);{%- endfilter -%}
+ This will return a "Hello World" body, but have the extra `X-Powered-By: Stack` header.
++ by stack +
+Provides a request session for subsequent middlewares. Based on the Silex SessionServiceProvider.
+ +Builder constructs a nested HttpKernelInterface
decorator tree. It models it as a stack of middlewares.
Builder constructs a nested HttpKernelInterface
decorator tree. It models it as a stack of middlewares.