如何在yii2中注册事件

时间:2015-03-30 15:48:51

标签: yii2

我想在我的模型中触发一些事件,如果我在index.php中通过app-> on注册我的事件,那么我就不会从事件对象中收到所需的$event->data

如何注册我的事件处理程序,所以当我调用触发器时,它将使用事件对象调用正确的函数。

代码示例:

namespace app\modules\Product\models\Product;

class Product extends Entity\Entity {
    public static function tableName() {
       return 'sometable';
    }

    public function afterFind() {
       parent::afterFind();
       $event = new yii\base\Event;
       $event->data = $this;

        $this->trigger('calculatePrice', $event);
    }

}

namespace app\modules\PriceRules\models;

class PriceRules extends yii\base\Model {
    public static function calculatePrice($event) {
        $entity = $event->data;
    }
}

//somehow register events

2 个答案:

答案 0 :(得分:0)

在方法Product中添加init此代码:

class Product extends Entity\Entity {
  public function init()
    {
        $this->on('calculatePrice', ['app\modules\PriceRules\models\PriceRules', 'calculatePrice']);        
    }
   ...
}

请参阅doc - http://www.yiiframework.com/doc-2.0/guide-concept-events.html

答案 1 :(得分:0)

我找到了解决方案。我将PriceRules模块放在bootstrap中,并在此处添加了此代码:

yii\base\Event::on(Product::className(), 'calculatePrice', [PriceRulesEvent::className(), 'calculatePrice']);
相关问题