How to use events in Yii
Asked Answered
P

2

8

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

Psychopathist answered 14/9, 2011 at 0:33 Comment(0)
G
16

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.

Gilder answered 14/9, 2011 at 17:35 Comment(1)
So where in the project structure should the clas live if I add it on the config file?Collogue
V
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();');
Valet answered 14/9, 2011 at 0:49 Comment(3)
can you do Yii::app()->onendRequest = function(){//do somthing} ;Psychopathist
not sure, I haven't used it in a while but mebbe it would in 5.3, you could try = return function() use ($event) {/*do somthing*/};Valet
create_function should never be used. Use an anonymous function instead.Conceptualism

© 2022 - 2024 — McMap. All rights reserved.