zf3 onRoute event listener

£可爱£侵袭症+ 提交于 2020-01-04 13:44:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!