There are some good guides out there explaining how to work with events and the ways to attach them to your components, but none (that I know) explain the following way to configure your events with CAction classes on your controllers the following way.
As you know, events are used by:
If we look at the magic method __set of CComponent, we will see that event handlers are actually set like properties.
Having that into account, the following is my quick tip to set your event handlers when working with CAction classes, which I think is far much better to organize your code in your controllers.
Lets write a simple CAction class for the example and save it as EMyAction.php:
class EMyAction extends CAction{ public function onTest($event){ $this->raiseEvent('onTest', $event); } public function run() { $event = new CEvent($this); $this->onTest($event); } }
Now in our controller, for the sake of the example, lets write a method handler and configure the action (assumed to be on actions folder under, which is in controllers folder).
// our event handler method, that, for simplicity, // we set it in our controller public function eventHandlerMethod($event) { echo 'TESTING Handler'; } // declaring actions and its event handlers public function actions() { return array( // test is the action name <controller/action> 'test'=>array( 'class'=>'actions.EMyAction', 'onTest'=>array($this,'eventHandlerMethod') ) ); }
And that's it, call the controller's action as you would with any other in your preferred browser to test the results.
Be the first person to leave a comment
Please login to leave your comment.