|
| 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