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

php, zend-framework2

Solution

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.

Problem

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...

Original source

Related problems