I'm sorry but I don't know about "auto hooks" but here is how event handling in Yii works:
This is the a test class which does nothing special, has just a function test()
which outputs some text. It could be anything, like a model, component or whatever:
class TestClass extends CComponent
{
public function test()
{
echo 'Running test()<br />';
echo 'Now firing event<br />';
$event = new TestEvent($this, 1, 'someTestParam'); // see TestEvent class constructor
$this->onTest($event);
}
public function onTest($event)
{
$this->raiseEvent('onTest', $event);
}
}
In method test()
we create the event object and pass it to our method onTest()
which raises the event.
The event object is a simple class that extends CEvent. We can use it to pass information about the event to the eventhandler:
class TestEvent extends CEvent
{
public $var1;
public $var2;
public function __construct(TestClass $sender, $var1, $var2)
{
parent::__construct($sender);
$this->var1 = $var1;
$this->var2 = $var2;
}
}
The controller action looks like this:
public function actionEventTesting()
{
// create a new class
$class = new TestClass();
// attach an event handler
$class->onTest[] = function($event) {
echo "Attached Event1 raised<br />";
var_dump($event);
};
// attach a 2nd event handler (note that this is another method of attaching as before)
$class->attachEventHandler('onTest', function($event) {
echo "Attached Event2 raised<br />";
var_dump($event);
});
// call our test method
$class->test();
}
Note that you can raise the event like so:
class TestClass extends CComponent
{
public function test()
{
echo 'Running test()<br />';
echo 'Now firing event<br />';
$event = new TestEvent($this, 1, 'someTestParam');
// this one is different as before
$this->raiseEvent('onTest', $event);
}
public function onTest($event)
{
// empty
}
}
I don't know why but you need the method onTest()
even if its empty. Otherwise you will get some exception when you try to attach an event handler to the object.
But you can put these "on" methods aside into an abstract class or something so they don't bother you.
Also note that you do not need to create your own event classes, you can simply use CEvent
directly and pass parameters to it:
public function test()
{
echo 'Running test()<br />';
echo 'Now firing event<br />';
$event = new CEvent($this, array('var1' => 1, 'var2' => 'someTestParam'));
$this->onTest($event);
}
You can also declare events in behaviours but that is a different story.