ZF2 Event Manager

I need to implement an event trigger in each of my modules when something specific happens. I also need that all other modules that should have done some work when this event is a trigger should be aware of this.

I am trying to create some common endpoint where I can send my triggers and where all the modules should listen on, but I have some problems figuring out how I can achieve this.

Any ideas?

+4
source share
2 answers

Based on the comments to @Andrew's answer, while your controller extends AbstractActionController (which most likely does), it already knows the EventManager, so you can simply fire any event that you like in the controller action by simply executing ...

 <?php namespace Application/Controller; // usual use statements omitted for brevity .. class IndexController extends AbstractActionController { public function indexAction() { // trigger MyEvent $this->getEventManager()->trigger('MyEvent', $this); } } 

To listen to this event in the bootstrap of some other module:

 public function onBootstrap(EventInterface $e) { $app = $e->getApplication(); // get the shared events manager $sem = $app->getEventManager()->getSharedManager(); // listen to 'MyEvent' when triggered by the IndexController $sem->attach('Application\Controller\IndexController', 'MyEvent', function($e) { // do something... }); } 
+14
source

Here are some good articles about this:

http://www.mwop.net/blog/266-Using-the-ZF2-EventManager.html

http://www.eschrade.com/page/zend-framework-2-event-manager/

It is very easy to get your modules to listen to an event that is a widely used application, and then perform some task at startup. In these two cases, there should be more than enough information to get you started.

If you give an example of what you want, I can help with an example of how you can do this.

+3
source

All Articles