Skip to content
This repository was archived by the owner on Jan 29, 2020. It is now read-only.

Commit 9db9358

Browse files
committed
add doc for middleware usage in "dispatch" event
1 parent 05e8db5 commit 9db9358

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

doc/book/middleware.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ a "controller" in the routing defaults, you provide "middleware":
2727
```php
2828
// Via configuration:
2929
return [
30-
'router' =>
30+
'router' =>
3131
'routes' => [
3232
'home' => [
3333
'type' => 'literal',
@@ -106,3 +106,45 @@ causing the application to short-circuit and return the response immediately.
106106
You can, however, return arbitrary values. If you do, the result is pushed into
107107
the `MvcEvent` as the event result, allowing later dispatch listeners to
108108
manipulate the results.
109+
110+
## Using Middleware in 'dispatch' Event
111+
112+
During Mvc Workflow, you can use the Middleware in 'dispatch' event by provide `Psr7Bridge`. For example, you have `AuthorizationMiddleware`:
113+
114+
```php
115+
namespace Application\Middleware;
116+
117+
class AuthorizationMiddleware
118+
{
119+
public function __invoke($request, $response, $next = null)
120+
{
121+
// handle authorization here...
122+
}
123+
}
124+
```
125+
126+
As the request and response in 'dispatch' event is a `Zend\Http` Request and Response object, we need the bridge to convert into PSR-7 Request and Response. To do that, you can do the following:
127+
128+
```php
129+
namespace Application;
130+
131+
use Application\Middleware\AuthorizationMiddleware;
132+
use Zend\Psr7Bridge\Psr7ServerRequest;
133+
use Zend\Psr7Bridge\Psr7Response;
134+
135+
class Module
136+
{
137+
public function onBootstrap($e)
138+
{
139+
$app = $e->getApplication();
140+
$eventManager = app->getEventManager();
141+
$services = app->getServiceManager();
142+
143+
$eventManager->attach('dispatch', function ($e) use ($services) {
144+
$request = Psr7ServerRequest::fromZend($e->getRequest());
145+
$response = Psr7Response::fromZend($e->getResponse());
146+
$result = ($services->get(AuthorizationMiddleware::class))($request, $response);
147+
}, 2);
148+
}
149+
}
150+
```

0 commit comments

Comments
 (0)