Yii2事件:如何使用行为添加多个事件处理程序&x27;s事件方法?
这是我的行为类Yii2事件:如何使用行为添加多个事件处理程序&x27;s事件方法?,yii2,yii-events,Yii2,Yii Events,这是我的行为类events()方法。当我触发一个事件时,会调用第二个处理程序,即sendmailhandler,它会忽略另一个处理程序。我相信,第二个会覆盖第一个。如何解决此问题,以便调用两个事件处理程序 // UserBehavior.php public function events() { return [ Users::EVENT_NEW_USER => [$this, 'anotherOne'],
events()
方法。当我触发一个事件时,会调用第二个处理程序,即sendmailhandler
,它会忽略另一个处理程序。我相信,第二个会覆盖第一个。如何解决此问题,以便调用两个事件处理程序
// 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
模型。我尝试使用model的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中包含类似的内容,而无需使用events()
您可以使用匿名函数在事件方法中附加处理程序:
ActiveRecord::EVENT_AFTER_UPDATE => function ($event) {
$this->deleteRemovalRequestFiles();
$this->uploadFiles();
}
ActiveRecord::EVENT_AFTER_UPDATE => function ($event) {
$this->deleteRemovalRequestFiles();
$this->uploadFiles();
}