You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.
Register an event handler at Object-Level
e.g inside the init method of a Model
// this should be inside your model class. For example User.php
public function init(){
$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
$this->on(self::EVENT_NEW_USER, [$this, 'notification']);
// first parameter is the name of the event and second is the handler.
// For handlers I use methods sendMail and notification
// from $this class.
parent::init(); // DON'T Forget to call the parent method.
}
taked from https://stackoverflow.com/questions/28575636/how-to-use-events-in-yii2
Register an event handler at Class-Level
To register event handlers at Class-Level a good place can be inside the bootstrap process.
So, you can put the registration code as
Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
Yii::debug(get_class($event->sender) . ' is inserted');
});
in a php file like the bootstrap.php
used in Advanced-Template or through configuration, with your custom component for example
see docs
(https://www.yiiframework.com/doc/guide/2.0/en/structure-applications#bootstrap or https://www.yiiframework.com/doc/guide/2.0/en/structure-extensions#bootstrapping-classes)
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.