Where to register event listeners

前端 未结 3 1427
醉梦人生
醉梦人生 2020-12-13 15:16

I\'m trying to use the Event System in CakePHP v2.1+

It appears to be quite powerful, but the documentation is somewhat vague. Triggering the event seems pretty stra

3条回答
  •  伪装坚强ぢ
    2020-12-13 16:04

    If you want to attach an event listener inside bootstrap.php file of your plugin, everything should work fine using the hints posted in the answers. Here is my code (which works properly):

    MyPlugin/Config/bootstrap.php:

    App::uses('CakeEventManager', 'Event');
    App::uses('MyEventListener', 'MyPlugin.Lib/Event');
    CakeEventManager::instance()->attach(new MyEventListener());
    

    MyPlugin/Lib/Event/MyEventListener.php:

    App::uses('CakeEventListener', 'Event');
    class MyEventListener implements CakeEventListener {
        ...
    }
    

    Event listeners related to MyPlugin are being registered only when the plugin is loaded. If I don't want to use the plugin, event listeners are not attached. I think this is a clean solution when you want to add some functionality in various places in your app using a plugin.

提交回复
热议问题