-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathexample.html
More file actions
44 lines (38 loc) · 1.86 KB
/
example.html
File metadata and controls
44 lines (38 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
---
layout: default
title: Example
nav_name: example
---
{% block content %}
<div class="example">
<h2>Middlewares</h2>
<p>Creating a new middleware is generally quite easy. The hardest part is grasping the decorator pattern.</p>
<p>A decorator is simply an object that wraps around an other object. In this case a middleware is a decorator for <code>HttpKernelInterface</code>. The decorator wraps around a kernel, and exposes the same interface.</p>
<p>Let's take a look at an <code>PoweredByStack</code> middleware, that adds a `X-Powered-By` header to all responses.</p>
<pre><code class="php">{%- 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 -%}</code></pre>
<p>This middleware takes a kernel in the constructor and delegates to this kernel from within <code>handle</code>. Then it augments the response. It <em>decorates</em> the <code>handle</code> call.</p>
<p>Here is an example of how you could use this middleware with Silex. Note that you can replace Silex with any kernel implementation.</p>
<pre><code class="php">{%- filter escape -%}$app = new Silex\Application();
$app->get('/', function () {
return 'Hello World!';
});
$app = new PoweredByStack($app);
Stack\run($app);{%- endfilter -%}</code></pre>
<p>This will return a "Hello World" body, but have the extra `X-Powered-By: Stack` header.</p>
</div>
{% endblock %}