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

add doc for middleware usage in "dispatch" event #94

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions doc/book/cookbook/using-middleware-in-dispatch-event.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Using Middleware in "dispatch" Event

During Mvc Workflow, you can use the Middleware in 'dispatch' event by provide `Psr7Bridge`. For example, you have `AuthorizationMiddleware`:

```php
namespace Application\Middleware;

class AuthorizationMiddleware
{
public function __invoke($request, $response, $next = null)
{
// handle authorization here...
}
}
```

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, and then, the result of invoked `AuthorizationMiddleware` above needs to be converted to `Zend\Http` Response if an instance of `Psr\Http\Message\ResponseInterface`. To do that, you can do the following:

```php
namespace Application;

use Application\Middleware\AuthorizationMiddleware;
use Psr\Http\Message\ResponseInterface;
use Zend\Psr7Bridge\Psr7ServerRequest;
use Zend\Psr7Bridge\Psr7Response;

class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$eventManager = $app->getEventManager();
$services = $app->getServiceManager();

$eventManager->attach('dispatch', function ($e) use ($services) {
$request = Psr7ServerRequest::fromZend($e->getRequest());
$response = Psr7Response::fromZend($e->getResponse());
$result = ($services->get(AuthorizationMiddleware::class))($request, $response, function() {});

if ($result instanceof ResponseInterface) {
return Psr7Response::toZend($result);
}
}, 2);
}
}
```
2 changes: 1 addition & 1 deletion doc/book/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ a "controller" in the routing defaults, you provide "middleware":
```php
// Via configuration:
return [
'router' =>
'router' =>
'routes' => [
'home' => [
'type' => 'literal',
Expand Down
2 changes: 2 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pages:
- Examples: examples.md
- 'Dispatching PSR-7 Middleware': middleware.md
- 'Migration Guide': migration.md
- Cookbook:
- 'Using Middleware in "dispatch" Event': cookbook/using-middleware-in-dispatch-event.md
site_name: zend-mvc
site_description: 'zend-mvc: MVC application provider'
repo_url: 'https://github.com/zendframework/zend-mvc'
Expand Down