如何在Yii中使用事件 [英] How to use events in Yii
问题描述
我想在onBeginRequest事件中运行一些代码.
我该在哪里做?我想我不应该在核心库代码中添加它.
我完全是Yii的菜鸟
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
推荐答案
如果要使用onBeginRequest和onEndRequest,可以通过在配置文件中添加以下几行来实现:
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'),
...
)
或者您可以内联
Yii::app()->onBeginRequest= array('Y', 'getStats');
Yii::app()->onEndRequest= array('Y', 'writeStats');
,其中Y
是类名,getStats
和writeStats
是此类的方法.
现在,假设您有一个这样声明的类Y
:
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
}
}
因此,对于每个请求,这两种方法都将自动运行.当然,您可以考虑为什么不简单地重载onBeginRequest方法?"但首先,事件使您无需扩展类即可运行某些重复的代码,而且还使您可以执行在不同位置声明的不同类的不同方法. 所以你可以添加
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');
在应用程序的任何其他部分使用
以及以前的事件处理程序,在处理请求之后,您将同时运行Y->writeStats
和YClass->someMethod
.这种行为使您可以创建几乎任何复杂的扩展组件,而无需更改源代码,也无需扩展Yii的基类.
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.
这篇关于如何在Yii中使用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!