Skip to content

Commit 62ceede

Browse files
committed
Start work on example page
1 parent 1697344 commit 62ceede

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

source/_views/default.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
<li {% if page.nav_name == "home" %} class="active" {% endif %}>
2222
<a href="{{ site.url }}/">Home</a>
2323
</li>
24+
<li {% if page.nav_name == "example" %} class="active" {% endif %}>
25+
<a href="{{ site.url }}/example/">Example</a>
26+
</li>
2427
<li {% if page.nav_name == "middlewares" %} class="active" {% endif %}>
2528
<a href="{{ site.url }}/middlewares/">Middlewares</a>
2629
</li>

source/example.html

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
---
2+
layout: default
3+
title: Example
4+
nav_name: example
5+
---
6+
{% block content %}
7+
<div class="examples">
8+
<h2>Creating middlewares</h2>
9+
<p>Creating a new middleware is generally quite easy. The hardest part is grasping the decorator pattern.</p>
10+
<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>
11+
<p>Let's take a look at an <code>Append</code> middleware, that appends a pre-configured string to all response bodies.</p>
12+
<pre><code class="php">{%- filter escape -%}use Symfony\Component\HttpFoundation\Request;
13+
use Symfony\Component\HttpKernel\HttpKernelInterface;
14+
15+
class Append implements HttpKernelInterface
16+
{
17+
protected $app;
18+
protected $append;
19+
20+
public function __construct(HttpKernelInterface $app, $append)
21+
{
22+
$this->app = $app;
23+
$this->append = $append;
24+
}
25+
26+
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
27+
{
28+
$response = $this->app->handle($request, $type, $catch);
29+
$response->setContent($response->getContent().$this->append);
30+
return $response;
31+
}
32+
}{%- endfilter -%}</code></pre>
33+
<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>
34+
<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>
35+
<pre><code class="php">{%- filter escape -%}$app = new Silex\Application();
36+
37+
$app->get('/', function () {
38+
return 'Hello World!';
39+
});
40+
41+
$app = new Append($app, ' FOO');
42+
43+
Stack\run($app);{%- endfilter -%}</code></pre>
44+
<p>This will return a response body of "Hello World! FOO" when accessing the <code>/</code> resource.</p>
45+
</div>
46+
{% endblock %}

0 commit comments

Comments
 (0)