Passing variables between Middlewares using zend-mvc

198 Views Asked by At

I'm trying to decipher how to properly blend variables between ZF3 Middleware under the latest release of zend-mvc.

Imagine a route like this:

'sandwich-test' => [
    'type' => \Zend\Router\Http\Literal::class,
    'options' => [
        'route' => '/events/sandwich',
        'defaults' => [
            'middleware' => [
                \Foo\Middleware\JsonWrappingMiddleware::class,
                \Foo\Middleware\TestMiddleware::class,
            ],
        ],
    ],
],

In my simple test, I'd like for JsonWrappingMiddleware to simply return in a JsonResponse, the variables returned by TestMiddleware.

Individually, this works:

use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\JsonResponse;

class JsonWrappingMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {

        return new JsonResponse(['c' => 'd']);
    }
}

...and...

use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\JsonResponse;

class TestMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        return new JsonResponse(['a' => 'b']);
    }
}

But then, how to make them work together to return

[ 'a' => 'b', 'c' => 'd', ]
1

There are 1 best solutions below

1
On

You are sending response twice, if you want a middleware to pass some data then use $request->withAttribute($name, $value): RequestInterface and then in second (or just simply last) middleware get that data and convert it to proper JsonResponse