zf3 onRoute事件监听器

时间:2017-02-10 15:25:01

标签: event-listener zf3

我的模型中有一段代码:

public function init(ModuleManager $manager)
{
    // Get event manager.
    $eventManager = $manager->getEventManager();
    $sharedEventManager = $eventManager->getSharedManager();
    // Register the event listener method.
    $sharedEventManager->attach(__NAMESPACE__, MvcEvent::EVENT_DISPATCH, [$this, 'myFunc'], 100);
}

// Event listener method.
public function myFunc(MvcEvent $event)
{
    echo 'it works!';
    exit;
}

调用侦听器。 虽然如果我将事件类型更改为MvcEvent :: EVENT_ROUTE,则不再调用侦听器。怎么解决?

1 个答案:

答案 0 :(得分:7)

因此,显然对象Zend \ EventManager \ EventManager为事件'dispatch'调用方法triggerListeners两次。将标识符设置为:

Array
(
    [0] => Zend\Mvc\Application
)

和第二个标识符设置为:

Array
(
    [0] => Zend\Mvc\Controller\AbstractController
    [1] => Application\Controller\IndexController
    [2] => Application
    [3] => Zend\Stdlib\DispatchableInterface
    [4] => Zend\EventManager\EventManagerAwareInterface
    [5] => Zend\EventManager\EventsCapableInterface
    [6] => Zend\Mvc\InjectApplicationEventInterface
    [7] => Zend\Mvc\Controller\AbstractActionController
)

因为我的侦听器是针对应用程序标识符定义的,所以它们在第二次调用时执行。 当调用'route'事件时,问题就开始了。它似乎只被调用一次,仅用于这组标识符:

Array
(
    [0] => Zend\Mvc\Application
)

之后,路由侦听器不会被执行,因为它们的标识符只是“应用程序”。解决它就足以用Zend \ Mvc \ Application标识符附加它们:

$sharedEventManager->attach('Zend\Mvc\Application', MvcEvent::EVENT_ROUTE, [$this, 'myFunc'], 100);