Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to event handlers in yii?

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?

like image 266
Ejaz Karim Avatar asked Jan 23 '26 06:01

Ejaz Karim


1 Answers

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"

}
like image 197
Ejaz Karim Avatar answered Jan 24 '26 19:01

Ejaz Karim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!