3

我的模型中有一段代码:

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,则不再调用侦听器。如何解决?

4

1 回答 1

8

因此,显然对象 Zend\EventManager\EventManager 为事件“调度”调用了 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
)

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

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

稍后,路由侦听器不会执行,因为它们的标识符只是“应用程序”。要解决这个问题,只需将它们附加到 Zend\Mvc\Application 标识符即可:

$sharedEventManager->attach('Zend\Mvc\Application', MvcEvent::EVENT_ROUTE, [$this, 'myFunc'], 100);
于 2017-02-13T13:50:37.983 回答