1

这是我的行为的类events()方法。当我触发事件第二个处理程序sendMailHanlder时,即被调用并且它忽略anotherOne. 我相信,第二个会覆盖第一个。如何解决此问题以便调用两个事件处理程序?

    // 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';
    }

需要注意的一件事是我将此行为附加到我的Users.php模型中。我尝试使用模型的init()方法添加两个处理程序。这样两个处理程序都被调用了。这是我的初始化代码。

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

3 回答 3

4

您可以覆盖 Behavior::attach() 以便您可以在 UserBehavior 中拥有类似的内容,而无需您的 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']);
    }
于 2015-02-19T03:26:24.260 回答
0

您可以使用匿名函数在事件方法中附加处理程序:

ActiveRecord::EVENT_AFTER_UPDATE => function ($event) {
    $this->deleteRemovalRequestFiles();
    $this->uploadFiles();
}
于 2019-02-22T09:55:43.087 回答
-1

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';
 }
于 2015-02-18T17:32:53.200 回答