zf2 :从 SharedEventManager 到控制器的参数

zf2 : Params from SharedEventManager to controller

我正在尝试向我的 zf2 应用添加 header 身份验证,将侦听器绑定到调度事件。

我的侦听器在调度时正确执行,returns 错误并停止响应传播。

问题是,当一切正常时,我想在请求中设置当前用户参数,以便我可以从控制器中获取它。

这是我现在的代码:

Module.php

public function onBootstrap(MvcEvent $event)
    {
        $app = $event->getApplication();
        $sm = $app->getServiceManager();
        $em = $app->getEventManager();

        $listener = $sm->get('MyAuthListener');
        $em->getSharedManager()->attach(
            'eventIdentifierForMyAbstractController',
            MvcEvent::EVENT_DISPATCH,
            $listener
        );
    }`

这个听众应该做这项工作。

public function __invoke(MvcEvent $event)
{

    $result = $this->adapter->authenticate();

    if (!$result->isValid()) {
            //Invalidation process
    }
    /validation Process
    $event->setParam('user', $result->getIdentity()); 
}

在我这边几乎一切正常。 $result->getIdentity() 给了我正确的身份。 $event->setParam('user', $result->getIdentity()) 在侦听器中正确设置事件的标识。

但是,在我的控制器中,当我正在做的时候: $this->getEvent()->getParam('user') 参数为空(即={}),但如果ivar_dump($result->getIdentity()),则object被完全创建。

我可以传递一个参数 $this->getEvent()->getParam('hello', 'hello'),这很好用。

我不明白为什么。文档说它需要混合类型,所以应该没问题。

如果您需要更多信息,请随时询问。

您必须为侦听器赋予更高的优先级,使其在调度控制器操作的侦听器之前执行。例如 100.

$em->getSharedManager()->attach(
    'eventIdentifierForMyAbstractController',
    MvcEvent::EVENT_DISPATCH,
    $listener,
    100
);