I am impressed by the flexibility of Yii events. I am new to Yii and I want to know how to pass parameters to Yii event handlers?

//i have onLogin event defined in the login model
public function onLogin($event)
{
  $this->raiseEvent("onLogin", $event);
}

I have a login handler defined in the handler class. This event handler method takes a parameter:

function loginHandler($param1)
{
  ...
}

But here, I am confused as to how to pass a parameter to the login event handler:

//i attach login handler like this.
$loginModel->onLogin = array("handlers", "loginHandler");
$e = new CEvent($this);
$loginModel->onLogin($e);

Am I doing something wrong? Is there another approach for this?

有帮助吗?

解决方案

Now I have an answer for my own question. CEvent class has a public property called params where we can add additional data while passing it to event handler.

//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"

}

其他提示

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');`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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top