0

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', ]
edigu
  • 9,878
  • 5
  • 57
  • 80
Saeven
  • 2,280
  • 1
  • 20
  • 33

1 Answers1

0

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

retest
  • 9
  • 1
  • 3
  • Hi. I understand the concept of returning, but I'm not sure how to combine these two to get the desired result. A code example would be great if you have time. – Saeven May 26 '17 at 14:54