我对Yii事件的灵活性印象深刻。我是新的Yii,我想知道如何传递参数到Yii事件处理程序?
//i have onLogin event defined in the login model
public function onLogin($event)
{
$this->raiseEvent("onLogin", $event);
}
我在处理程序类中定义了一个登录处理程序。这个事件处理程序方法接受一个参数:
function loginHandler($param1)
{
...
}
但是在这里,我很困惑如何将参数传递给登录事件处理程序:
//i attach login handler like this.
$loginModel->onLogin = array("handlers", "loginHandler");
$e = new CEvent($this);
$loginModel->onLogin($e);
我做错了什么吗?还有别的办法吗?
现在我对自己的问题有了答案。CEvent类有一个叫做params的公共属性,我们可以在传递给事件处理程序时添加额外的数据。
//while creating new instance of an event I could do this
$params = array("name" => "My Name");
$e = new CEvent($this, $params);
$loginModel->onLogin($e);
//adding second parameter will allow me to add data which can be accessed in
// event handler function. loginHandler in this case.
function loginHandler($event)// now I have an event parameter.
{
echo $event->params['name']; //will print : "My Name"
}
如果你想使用onBeginRequest和onEndRequest,你可以通过添加下面的行到你的配置文件:
return array (
'onBeginRequest'=>array('Y', 'getStats'),
'onEndRequest'=>array('Y', 'writeStats'),
)
或者内联
Yii::app()->onBeginRequest= array('Y', 'getStats');
Yii::app()->onEndRequest= array('Y', 'writeStats');`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方法?"但是首先,事件允许你不扩展类来运行一些重复的代码,而且它们允许你执行在不同地方声明的不同类的不同方法。所以你可以加上
Yii::app()->onEndRequest= array('YClass', 'someMethod');
在应用程序的任何其他部分以及先前的事件处理程序中,您将在请求处理后同时运行Y->writeStats
和YClass->someMethod
。使用behavior,您可以创建几乎任何复杂性的扩展组件,而无需更改源代码,也无需扩展Yii的基类。