问题
I have a piece of code in my model:
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;
}
The listener is invoked. Although if I change event type to MvcEvent::EVENT_ROUTE the listener is not invoked any more. How to solve it?
回答1:
So, apparently object Zend\EventManager\EventManager calls method triggerListeners for event 'dispatch' twice. Once with identifiers set as:
Array
(
[0] => Zend\Mvc\Application
)
and Second with identifiers set as:
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
)
Because my listeners are defined for Application identifier they are executed during 2nd call. The problem starts when call is made for 'route' event. It seems like it is called only once, just for this set of identifiers:
Array
(
[0] => Zend\Mvc\Application
)
Then later, the route listeners are not executed, because their identifier is just 'Application'. To solve it is just enough to attach them with Zend\Mvc\Application identifier:
$sharedEventManager->attach('Zend\Mvc\Application', MvcEvent::EVENT_ROUTE, [$this, 'myFunc'], 100);
来源:https://stackoverflow.com/questions/42162931/zf3-onroute-event-listener