|
| 1 | +# Session Middleware |
| 2 | + |
| 3 | +mezzio-session provides middleware consuming |
| 4 | +[PSR-7](http://www.php-fig.org/psr/psr-7/) HTTP message instances, via |
| 5 | +implementation of [PSR-15](https://www.php-fig.org/psr/psr-15/) |
| 6 | +interfaces. |
| 7 | + |
| 8 | +This middleware composes a [persistence](persistence.md) instance, and uses that |
| 9 | +in order to generate a session container, which it pushes into the request it |
| 10 | +delegates to the next middleware. Once a response is returned, it uses the |
| 11 | +persistence instance to persist the session data and provide information back to |
| 12 | +the client. |
| 13 | + |
| 14 | +The above two paragraphs are longer than the body of the middleware |
| 15 | +implementation: |
| 16 | + |
| 17 | +```php |
| 18 | +namespace Mezzio\Session; |
| 19 | + |
| 20 | +use Psr\Http\Message\ServerRequestInterface; |
| 21 | +use Psr\Http\Message\ResponseInterface; |
| 22 | +use Psr\Http\Server\MiddlewareInterface; |
| 23 | +use Psr\Http\Server\RequestHandlerInterface; |
| 24 | + |
| 25 | +class SessionMiddleware implements MiddlewareInterface |
| 26 | +{ |
| 27 | + public const SESSION_ATTRIBUTE = 'session'; |
| 28 | + |
| 29 | + private $persistence; |
| 30 | + |
| 31 | + public function __construct(SessionPersistenceInterface $persistence) |
| 32 | + { |
| 33 | + $this->persistence = $persistence; |
| 34 | + } |
| 35 | + |
| 36 | + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface |
| 37 | + { |
| 38 | + $session = new LazySession($this->persistence, $request); |
| 39 | + $response = $handler->handle( |
| 40 | + $request |
| 41 | + ->withAttribute(self::SESSION_ATTRIBUTE, $session) |
| 42 | + ->withAttribute(SessionInterface::class, $session) |
| 43 | + ); |
| 44 | + return $this->persistence->persistSession($session, $response); |
| 45 | + } |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +## Configuration |
| 50 | + |
| 51 | +This package provides a factory for `Mezzio\Session\SessionMiddleware` |
| 52 | +via `Mezzio\Session\SessionMiddlewareFactory`; this factory is |
| 53 | +auto-wired if you are using Mezzio and the laminas-component-installer Composer |
| 54 | +plugin. If not, you will need to wire these into your application. |
| 55 | + |
| 56 | +The factory depends on one service: `Mezzio\Session\SessionPersistenceInterface`. |
| 57 | +You will need to either wire in your persistence implementation of choice, or |
| 58 | +have the package providing it do so for you. |
| 59 | + |
| 60 | +## Adding the middleware to your application |
| 61 | + |
| 62 | +You may pipe this middleware anywhere in your application. If you want to have |
| 63 | +it available anywhere, pipe it early in your application, prior to any routing. |
| 64 | +As an example, within Mezzio, you could pipe it in the `config/pipeline.php` |
| 65 | +file: |
| 66 | + |
| 67 | +```php |
| 68 | +$app->pipe(\Mezzio\Session\SessionMiddleware::class); |
| 69 | +$app->pipe(\Mezzio\Router\Middleware\RouteMiddleware::class); |
| 70 | +``` |
| 71 | + |
| 72 | +This will generally be an inexpensive operation; since the middleware uses a |
| 73 | +`LazySession` instance, unless your persistence implementation does any work in |
| 74 | +its constructor, the cost is just that of instantiating a few objects. |
| 75 | + |
| 76 | +However, it's often useful to specifically include such middleware directly in |
| 77 | +the routed middleware pipelines, to ensure other developers are aware of its |
| 78 | +presence in that route's workflow. |
| 79 | + |
| 80 | +Within Mezzio, you can do this when routing, in your `config/routes.php` |
| 81 | +file, or within a [delegator factory](https://docs.mezzio.dev/mezzio/cookbook/autowiring-routes-and-pipelines/#delegator-factories): |
| 82 | + |
| 83 | +```php |
| 84 | +$app->post('/login', [ |
| 85 | + \Mezzio\Session\SessionMiddleware::class, |
| 86 | + \User\Middleware\LoginHandler::class |
| 87 | +]); |
| 88 | +``` |
| 89 | + |
| 90 | +## Retrieving the session in your own middleware |
| 91 | + |
| 92 | +Whilst it is trivial to retrieve the initialised session from the request with `$session = $request->getAttribute(SessionInterface::class);`, static analysers cannot automatically infer the value assigned to `$session`. |
| 93 | + |
| 94 | +To provide a convenient and type safe way to retrieve the session from the current request without manually asserting its type, `SessionRetrieval::fromRequest($request)` can be called so that you can use the request without further assertions. |
| 95 | + |
| 96 | +Furthermore, a static method exists to optionally retrieve a session when you cannot be sure the middleware has previously been piped: `SessionRetrieval::fromRequestOrNull($request)` |
| 97 | + |
| 98 | +```php |
| 99 | +namespace My\NameSpace; |
| 100 | + |
| 101 | +use Mezzio\Session\Exception\SessionNotInitializedException; |
| 102 | +use Mezzio\Session\RetrieveSession; |
| 103 | +use Psr\Http\Message\ResponseInterface; |
| 104 | +use Psr\Http\Message\ServerRequestInterface; |
| 105 | +use Psr\Http\Server\RequestHandlerInterface; |
| 106 | + |
| 107 | +class MyRequestHandler implements RequestHandlerInterface { |
| 108 | + |
| 109 | + // ... |
| 110 | + |
| 111 | + public function handle(ServerRequestInterface $request) : ResponseInterface |
| 112 | + { |
| 113 | + try { |
| 114 | + $session = RetrieveSession::fromRequest($request); |
| 115 | + } catch (SessionNotInitializedException $error) { |
| 116 | + // Handle the uninitialized session: |
| 117 | + return $this->redirectToLogin(); |
| 118 | + } |
| 119 | + |
| 120 | + $value = $session->get('SomeKey'); |
| 121 | + $this->templateRenderer->render('some:template', ['value' => $value]); |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +class AnotherRequestHandler implements RequestHandlerInterface { |
| 126 | + |
| 127 | + // ... |
| 128 | + |
| 129 | + public function handle(ServerRequestInterface $request) : ResponseInterface |
| 130 | + { |
| 131 | + $session = RetrieveSession::fromRequestOrNull($request); |
| 132 | + if (! $session) { |
| 133 | + // Handle the uninitialized session: |
| 134 | + return $this->redirectToLogin(); |
| 135 | + } |
| 136 | + |
| 137 | + $value = $session->get('SomeKey'); |
| 138 | + $this->templateRenderer->render('some:template', ['value' => $value]); |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +``` |
0 commit comments