How to use events in Yii

Itay Moav -Malimovka picture Itay Moav -Malimovka · Sep 14, 2011 · Viewed 8.7k times · Source

I want to run some code in the onBeginRequest event.
Where do I do that? I assume I am not suppose to add this in the core library code.
I am a totally noob in Yii

Answer

Johnatan picture Johnatan · Sep 14, 2011

If you want to use onBeginRequest and onEndRequest you can do it by adding the next lines into your config file:

return array (
...
'onBeginRequest'=>array('Y', 'getStats'),
'onEndRequest'=>array('Y', 'writeStats'),
...
)

or you can do it inline

Yii::app()->onBeginRequest= array('Y', 'getStats');
Yii::app()->onEndRequest= array('Y', 'writeStats');

where Y is a classname and getStats and writeStats are methods of this class. Now imagine you have a class Y declared like this:

class Y {
    public function getStats ($event) {
        // Here you put all needed code to start stats collection
    }
    public function writeStats ($event) {
        // Here you put all needed code to save collected stats
    }
}

So on every request both methods will run automatically. Of course you can think "why not simply overload onBeginRequest method?" but first of all events allow you to not extend class to run some repeated code and also they allow you to execute different methods of different classes declared in different places. So you can add

Yii::app()->onEndRequest= array('YClass', 'someMethod');

at any other part of your application along with previous event handlers and you will get run both Y->writeStats and YClass->someMethod after request processing. This with behaviors allows you create extension components of almost any complexity without changing source code and without extension of base classes of Yii.