Chris@0
|
1 # Stack/Builder
|
Chris@0
|
2
|
Chris@0
|
3 Builder for stack middlewares based on HttpKernelInterface.
|
Chris@0
|
4
|
Chris@0
|
5 Stack/Builder is a small library that helps you construct a nested
|
Chris@0
|
6 HttpKernelInterface decorator tree. It models it as a stack of middlewares.
|
Chris@0
|
7
|
Chris@0
|
8 ## Example
|
Chris@0
|
9
|
Chris@0
|
10 If you want to decorate a [silex](https://github.com/fabpot/Silex) app with
|
Chris@0
|
11 session and cache middlewares, you'll have to do something like this:
|
Chris@0
|
12
|
Chris@0
|
13 ```php
|
Chris@0
|
14 use Symfony\Component\HttpKernel\HttpCache\Store;
|
Chris@0
|
15
|
Chris@0
|
16 $app = new Silex\Application();
|
Chris@0
|
17
|
Chris@0
|
18 $app->get('/', function () {
|
Chris@0
|
19 return 'Hello World!';
|
Chris@0
|
20 });
|
Chris@0
|
21
|
Chris@0
|
22 $app = new Stack\Session(
|
Chris@0
|
23 new Symfony\Component\HttpKernel\HttpCache\HttpCache(
|
Chris@0
|
24 $app,
|
Chris@0
|
25 new Store(__DIR__.'/cache')
|
Chris@0
|
26 )
|
Chris@0
|
27 );
|
Chris@0
|
28 ```
|
Chris@0
|
29
|
Chris@0
|
30 This can get quite annoying indeed. Stack/Builder simplifies that:
|
Chris@0
|
31
|
Chris@0
|
32 ```php
|
Chris@0
|
33 $stack = (new Stack\Builder())
|
Chris@0
|
34 ->push('Stack\Session')
|
Chris@0
|
35 ->push('Symfony\Component\HttpKernel\HttpCache\HttpCache', new Store(__DIR__.'/cache'));
|
Chris@0
|
36
|
Chris@0
|
37 $app = $stack->resolve($app);
|
Chris@0
|
38 ```
|
Chris@0
|
39 As you can see, by arranging the layers as a stack, they become a lot easier
|
Chris@0
|
40 to work with.
|
Chris@0
|
41
|
Chris@0
|
42 In the front controller, you need to serve the request:
|
Chris@0
|
43
|
Chris@0
|
44 ```php
|
Chris@0
|
45 use Symfony\Component\HttpFoundation\Request;
|
Chris@0
|
46
|
Chris@0
|
47 $request = Request::createFromGlobals();
|
Chris@0
|
48 $response = $app->handle($request)->send();
|
Chris@0
|
49 $app->terminate($request, $response);
|
Chris@0
|
50 ```
|
Chris@0
|
51 Stack/Builder also supports pushing a `callable` on to the stack, for situations
|
Chris@0
|
52 where instantiating middlewares might be more complicated. The `callable` should
|
Chris@0
|
53 accept a `HttpKernelInterface` as the first argument and should also return a
|
Chris@0
|
54 `HttpKernelInterface`. The example above could be rewritten as:
|
Chris@0
|
55
|
Chris@0
|
56 ```php
|
Chris@0
|
57 $stack = (new Stack\Builder())
|
Chris@0
|
58 ->push('Stack\Session')
|
Chris@0
|
59 ->push(function ($app) {
|
Chris@0
|
60 $cache = new HttpCache($app, new Store(__DIR__.'/cache'));
|
Chris@0
|
61 return $cache;
|
Chris@0
|
62 })
|
Chris@0
|
63 ;
|
Chris@0
|
64 ```
|
Chris@0
|
65
|
Chris@0
|
66 ## Inspiration
|
Chris@0
|
67
|
Chris@0
|
68 * [Rack::Builder](http://rack.rubyforge.org/doc/Rack/Builder.html)
|
Chris@0
|
69 * [HttpKernel middlewares](https://igor.io/2013/02/02/http-kernel-middlewares.html)
|