|
| 1 | +# Using middleware within event listeners |
| 2 | + |
| 3 | +Within the MVC workflow, you can use middleware within event listeners by |
| 4 | +converting the request and response objects composed in the event to PSR-7 |
| 5 | +equivalents using [zend-psr7bridge](https://github.com/zendframework/zend-psr7bridge). |
| 6 | + |
| 7 | +As an example, consider the following `AuthorizationMiddleware`: |
| 8 | + |
| 9 | +```php |
| 10 | +namespace Application\Middleware; |
| 11 | + |
| 12 | +use Psr\Http\Message\ServerRequestInterface as RequestInterface; |
| 13 | +use Psr\Http\Message\ResponseInterface; |
| 14 | + |
| 15 | +class AuthorizationMiddleware |
| 16 | +{ |
| 17 | + public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next = null) |
| 18 | + { |
| 19 | + // handle authorization here... |
| 20 | + } |
| 21 | +} |
| 22 | +``` |
| 23 | + |
| 24 | +Since the request and response composed in `MvcEvent` instances are specifically |
| 25 | +from zend-http, we will use zend-psr7bridge to convert them to PSR-7 |
| 26 | +equivalents. As an example, consider the following module declaration, which |
| 27 | +registers a `dispatch` listener to invoke the above middleware: |
| 28 | + |
| 29 | +```php |
| 30 | +namespace Application; |
| 31 | + |
| 32 | +use Psr\Http\Message\ResponseInterface; |
| 33 | +use Zend\Psr7Bridge\Psr7ServerRequest; |
| 34 | +use Zend\Psr7Bridge\Psr7Response; |
| 35 | + |
| 36 | +class Module |
| 37 | +{ |
| 38 | + public function onBootstrap($e) |
| 39 | + { |
| 40 | + $app = $e->getApplication(); |
| 41 | + $eventManager = $app->getEventManager(); |
| 42 | + $services = $app->getServiceManager(); |
| 43 | + |
| 44 | + $eventManager->attach($e::EVENT_DISPATCH, function ($e) use ($services) { |
| 45 | + $request = Psr7ServerRequest::fromZend($e->getRequest()); |
| 46 | + $response = Psr7Response::fromZend($e->getResponse()); |
| 47 | + $done = function ($request, $response) { |
| 48 | + }; |
| 49 | + |
| 50 | + $result = ($services->get(Middleware\AuthorizationMiddleware::class))( |
| 51 | + $request, |
| 52 | + $response, |
| 53 | + $done |
| 54 | + ); |
| 55 | + |
| 56 | + if ($result) { |
| 57 | + return Psr7Response::toZend($result); |
| 58 | + } |
| 59 | + }, 2); |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
0 commit comments