0

我想在 MvcEvent::EVENT_DISPATCH 之前做一些逻辑,但是如果我将优先级设置为 1 以上,MvcEvent::getTarget() 函数将返回 Mvc\Application 的对象而不是 Controller:

$e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, array($this, 'routing'), 100);

如果我将优先级设置为负值,我会得到 Controller 对象,但它会在动作函数之后触发。在这种情况下如何获取 Controller 对象?

4

2 回答 2

0
// in your Module
public function onBootstrap(MvcEvent $e)
{
    $e->getApplication()
      ->getEventManager()
      ->getSharedManager()
      ->attach(
            'Zend\Stdlib\DispatchableInterface', 
            MvcEvent::EVENT_DISPATCH, array($this, 'onDispatch'), 
            2
        );
}

public function onDispatch(MvcEvent $a)
{
    $target = $a->getTarget();
}
于 2013-06-06T08:10:55.570 回答
0

您可以使用MvcEvent::getRouteMatch()来确定将分派哪个控制器(如果有),或者通过覆盖来附加到控制器本身内部的控制器事件管理器AbstractActionController:setEventManager()

IE:

// in your controller

public function setEventManager(EventManagerInterface $events)
{
    parent::setEventManager($events);

    $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100);
}

public function preDispatch(MvcEvent $event)
{
    // your custom logic here
}
于 2013-06-06T08:57:59.050 回答