我想在我的模型中触发一些事件,如果我在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
答案 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']);