Using events with CAction classes

Introduction

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:

  • Declaring an event in your component adding its method (ie. function onClick($event))
  • Attach it to event handlers (ie. $object->onClick=array($handlerObject,'staticmethod');)
  • Raising it from your component to call all subscribed handlers (ie. $this->raiseEvent('onClick',$event)). Remember, that for a handler, you can write an object with static methods, an object with a method, create a function (create_function) and even attach a function directly (since PHP 5.3)
Tip

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.

The CAction class

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);
	}
}
The Controller

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.

Links

Chinese Version