Using events with CAction classes

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

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.

9 0
9 followers
Viewed: 16 698 times
Version: Unknown (update)
Category: Tips
Written by: Antonio Ramirez
Last updated by: 张 迪
Created on: Oct 13, 2011
Last updated: 6 years ago
Update Article

Revisions

View all history

Related Articles