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



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)