使用zend-mvc在中间件之间传递变量

时间:2017-05-25 19:46:58

标签: zend-framework3 zend-framework-mvc zend-expressive

我正在尝试破解如何在最新版本的zend-mvc下正确混合ZF3中间件之间的变量。

想象一下这样的路线:

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

在我的简单测试中,我希望JsonWrappingMiddleware简单地返回一个JsonResponse,即TestMiddleware返回的变量。

单独地,这有效:

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']);
    }
}

...和...

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']);
    }
}

但是,如何让他们共同努力回归

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

1 个答案:

答案 0 :(得分:0)

您要发送响应两次,如果您希望中间件传递某些数据然后使用$request->withAttribute($name, $value): RequestInterface然后在第二个(或者只是最后)中间件获取该数据并将其转换为适当的JsonResponse