Reputation: 1201
I use zend-expressive and i would like to pass data from one middelware to another. e.g. in config/routes.php I've
[
'name' => 'v1.item.list',
'path' => '/item',
'allowed_methods' => ['GET'],
'middleware' => [
Api\V1\Action\ItemListAction::class,
Application\Middleware\JsonRenderMiddleware::class
]
],
in Api\V1\Action\ItemListAction I'm preparin some data from databases and I like to pass $itemsList to another middelware
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
$parameters = new ListParameters($request->getQueryParams());
$itemsList = $this->commandBus->handle(new ItemListCommand($parameters));
return $next($request, $response);
}
and in Application\Middleware\JsonRenderMiddleware I would like get $itemsList and return in json format:
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
return new JsonResponse($itemsList);
}
How is the best way? Only commandBus or is other solution in this framework?
Upvotes: 1
Views: 532
Reputation:
There are several ways to go here.
Usually you would return a Zend\Diactoros\Response\JsonResponse in your action. Normally you want to extend that class and transform that list into something more useful. I wouldn't use the request to pass data like this.
However I see that you are using a command bus. I haven't worked with that yet, but you might want to have a look at https://github.com/prooph/proophessor-do. That's a nice example on how they use CQRS and Event Sourcing with expressive.
Upvotes: 0
Reputation: 9008
You could use the attributes of the $request
.
In Api\V1\Action\ItemListAction
you could do
$request = $request->withAttribute('list', $itemsList);
and then retrieve it in Application\Middleware\JsonRenderMiddleware
using
$itemsList = $request->getAttribute('list');
The only drawback of this solution is that you are creating a dependency between the two middlewares, because the second one will break if the $request
does not have a list
attribute
Upvotes: 3