More on CakePHP event listening

Posted on June 27, 2012

Since my last foray into events in CakePHP, I’ve made a bit more headway into events. Here’s my report.The challenge this time was to create a listener for a plugin. To do this, I’m using the fact that a plugin can have its own bootstrap file. To do that, when you load the plugin, add on (array(‘bootstrap’ => true). Anyway, here’s the actual code:

// MyPlugin/Config/bootstrap.php
App::uses('CakeEventManager', 'Event');
App::uses('MyPluginListener', 'MyPlugin.Event');
 
CakeEventManager::instance()->attach(new MyPluginListener());

Then…

// MyPlugin/Event/MyPluginListener.php
App::uses('CakeEventListener', 'Event');
 
class MyPluginListener implements CakeEventListener {
 
    public function implementedEvents() {
        return array(
            'View.anEvent'        => 'handleAnEvent',
        );
    }
 
    public function handleAnEvent($event) {
        // do stuff
    }
}

It’s really not all that difficult, but I haven’t found anyone else who has written this up. This is for separate plugins, but I suppose you could toss similar code into your main app’s bootstrap. You could also use the above code and combine it with the glob() approach I detailed in my other post.

Leave a Reply

Your email address will not be published. Required fields are marked *