How to use events in Yii

2019-02-07 04:19发布

问题:

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

回答1:

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.



回答2:

I believe you can do this pretty much anywhere in your files before any output has started, so it should work in a controller, view or custom class, usually located in the "protected" folder in a Yii web app. FYI, those files are not core files and can be (nearly) freely edited, as apposed to the Yii framework files (as referenced by the "$yii" var in the bootstrap index.php file).

the functions look like:

Yii::app()->onbeginRequest = create_function('$event', 'return function_name_a();');
Yii::app()->onendRequest = create_function('$event', 'return function_name_b();');