简体   繁体   中英

How to use ZF2's EventManager over multiple classes (and modules)?

I am having the following setup: In a controller I trigger an event and I want to attach multiple listeners to it at other places.

Currently I have the following listener in my onBootstrap :

$e->getApplication()->getServiceManager()->get('EventManager')->attach('*', function($e) {
    var_dump($e->getName());
});

The following piece of code as a factory :

'Application\Controller\Foo' => function(ControllerManager $cm) {
    $eventManager = $cm->getServiceLocator()->get('EventManager');
    $controller = new \Application\Controller\FooController();
    $controller->setEventManager($eventManager);
    return $controller;
},

And finally the following trigger within my controller :

$this->getEventManager()->trigger('foo-finished', 'finishedAction', array(
    'obj' => $foo->someObject()
));

So it should both be the same EventManager as I receive it from the service locator and inject it into the controller. Still I get no output at all. I also tried using $e->getApplication()->getEventManager() when attaching to events, but this only gives me the ZF internal events.

I read about the SharedEventManager , but I do not fully understand why I should pass a context. I tried it like this (which is as I understood it), but still no output.

$e->getApplication()->getServiceManager()->get('EventManager')
    ->getSharedManager()
    ->attach('finishedAction', '*', function() { ... });

So, what am I doing wrong? I just want to trigger events and catch them in possibly different modules, but it seems to be made so complicated...

By default the EventManager service is not shared, this means that every time you call $serviceLocator->get('EventManager') you will get a different instance, that's why you should use the SharedEventManager - take a look at @Crisp's link to see how to use it.

One more tip: Don't try to inject the Mvc EventManager in your objects, each object should trigger their own events.

The following worked for me (not the order of getEventManager and getSharedManager), also note the order of event name and the context (or identifier).

$e->getApplication()->getEventManager()->getSharedManager()->attach('*', 'finishedAction', function() { ... });

Regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM