Yii2 Events: How to add multiple event handlers using behavior's events method?

2.4k views Asked by At

Here is my Behavior's class events() method. When I trigger an event second handler i.e. sendMailHanlder gets called and it ignores anotherOne. I believe, the second one overwrites first one. How do I solve this problem so that both event handlers get called?

    // UserBehavior.php
    public function events()
    {
        return [
            Users::EVENT_NEW_USER => [$this, 'anotherOne'],
            Users::EVENT_NEW_USER => [$this, 'sendMailHanlder'],
        ];
    }
    // here are two handlers
    public function sendMailHanlder($e)
    {
        echo ";
    }
    public function anotherOne($e)
    {
        echo 'another one';
    }

One thing to notice is that I'm attaching this behavior to my Users.php model. I tried adding both handlers using model's init() method. That way both handlers got called. Here is my init code.

public function init()
{
    $this->on(self::EVENT_NEW_USER, [$this, 'anotherOne']);
    $this->on(self::EVENT_NEW_USER, [$this, 'sendMailHanlder']);
}
3

There are 3 answers

0
jovani On BEST ANSWER

You can override Behavior::attach() so you can have something like this in your UserBehavior and no need of your events()

    // UserBehavior.php
    public function attach($owner)
    {
        parent::attach($owner);
        $owner->on(self::EVENT_NEW_USER, [$this, 'anotherOne']);
        $owner->on(self::EVENT_NEW_USER, [$this, 'sendMailHanlder']);
    }
0
vitalik_74 On

You should not use equal event names. Use this instead:

 public function events()
 {
     return [
         Users::EVENT_NEW_USER => [$this, 'sendMailHanlder'],
     ];
 }

 // Here are two handlers
 public function sendMailHanlder($e)
 {
     echo '';
     $this->anotherOne($e);
 }

 public function anotherOne($e)
 {
     echo 'another one';
 }
0
Amirreza Yeganegi On

You can use anonymous function for attaching handler's in events method :

ActiveRecord::EVENT_AFTER_UPDATE => function ($event) {
    $this->deleteRemovalRequestFiles();
    $this->uploadFiles();
}