ZF2 Shared Modules Event Manager

2019-03-16 19:36发布

I need to implement in each of my modules an event trigger when something specific happens. I also need that all the other modules that must to do some work when that event is trigger, be aware of it.

I'm trying to create some common endpoint where I can send my triggers, and where all the modules need to be listening, but I'm having some trouble figuring out how can I achieve that.

Any ideas?

2条回答
Summer. ? 凉城
2楼-- · 2019-03-16 19:43

There's a couple of good articles on this:

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

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

It's quite easy to make your modules listen to an event which is application wide, and then perform some task when triggered. There should be more than enough info in those two to get you started.

If you give an example of what you want I can help with an example of how you can go about it.

查看更多
forever°为你锁心
3楼-- · 2019-03-16 20:02

Based on the comments to @Andrew's answer, as long as your controller extends the AbstractActionController (which it most likely does) it's already EventManager aware, so you can just go ahead and trigger any event you like in a controller action simply by doing...

<?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 that event in the bootstrap of some other module, do the following

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...
    });
}
查看更多
登录 后发表回答