Search code examples
phpyiiyii-events

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?


Solution

  • 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"
    
    }