Yii2 事件:如何使用行为的事件方法添加多个事件处理程序?
Yii2 Events: How to add multiple event handlers using behavior's events method?
这是我的行为的 class 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']);
}
您不应使用相同的事件名称。改用这个:
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';
}
您可以覆盖 Behavior::attach() 这样您就可以在您的 UserBehavior 中拥有类似的东西而无需您的事件 ()
// 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']);
}
您可以使用匿名函数在事件方法中附加处理程序:
ActiveRecord::EVENT_AFTER_UPDATE => function ($event) {
$this->deleteRemovalRequestFiles();
$this->uploadFiles();
}
这是我的行为的 class 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']);
}
您不应使用相同的事件名称。改用这个:
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';
}
您可以覆盖 Behavior::attach() 这样您就可以在您的 UserBehavior 中拥有类似的东西而无需您的事件 ()
// 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']);
}
您可以使用匿名函数在事件方法中附加处理程序:
ActiveRecord::EVENT_AFTER_UPDATE => function ($event) {
$this->deleteRemovalRequestFiles();
$this->uploadFiles();
}