How to use ZF2 EventManager for several classes (and modules)?

I have the following setting: in the controller, I fire an event, and I want to connect several listeners to it in other places.

I currently have the following listener in my onBootstrap :

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

The following code snippet is like 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 next trigger in my controller :

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

Therefore, it must be the same EventManager , as I get it from the service locator and insert it into the controller. However, I am not getting any output. I also tried using $e->getApplication()->getEventManager() when connecting to events, but this only gives me ZF internal events.

I read about the SharedEventManager , but I don't quite understand why I have to pass the context. I tried it this way (it was 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 fire events and catch them in possibly different modules, but it seems that they are made so complex ...

+4
source share
2 answers

By default, the EventManager service EventManager not shared, which means that every time you call $serviceLocator->get('EventManager') , you will get a different instance, so you should use the SharedEventManager - take a look at @Crisp to find out how use.

One more tip: do not try to embed Mvc EventManager into your objects, each object should fire its own events.

+4
source

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

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

Hello!

0
source

All Articles