我想在 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中如何使用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!