2

Trying to learn events in Yii 2. I found a few resources. The link I got more attention is here.

How to use events in yii2?

In the first comment itself he explains with an example. Say for an instance we have 10 things to do after registration - events comes handy in that situation.

Calling that function is a big deal? The same thing is happening inside the model init method:

$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
$this->on(self::EVENT_NEW_USER, [$this, 'notification']);

My question is what is the point of using events? How should I get full benefit of using them. Please note this question is purely a part of learning Yii 2. Please explain with an example. Thanks in advance.

3

1 Answer 1

3

I use triggering events for written (by default) events like before validation or before deletion. Here's an example why such things are good.

Imagine that you have some users. And some users (administrators, for example) can edit other users. But you want to make sure that specific rules are being followed (let's take this: Only main administrator can create new users and main administrator cannot be deleted). Then what you can do is use these written default events.

In User model (assuming User models holds all users) you can write init() and all additional methods you have defined in init():

public function init()
{
    $this->on(self::EVENT_BEFORE_DELETE, [$this, 'deletionProcess']);
    $this->on(self::EVENT_BEFORE_INSERT, [$this, 'insertionProcess']);
    parent::init();
}

public function deletionProcess()
{
    // Operations that are handled before deleting user, for example:
    if ($this->id == 1) {
        throw new HttpException('You cannot delete main administrator!');
    }
}

public function insertionProcess()
{
    // Operations that are handled before inserting new row, for example:
    if (Yii::$app->user->identity->id != 1) {
        throw new HttpException('Only the main administrator can create new users!');
    }
}

Constants like self::EVENT_BEFORE_DELETE are already defined and, as the name suggests, this one is triggered before deleting a row.

Now in any controller we can write an example that triggers both events:

public function actionIndex()
{
    $model = new User();
    $model->scenario = User::SCENARIO_INSERT;
    $model->name = "Paul";
    $model->save(); // `EVENT_BEFORE_INSERT` will be triggered

    $model2 = User::findOne(2);
    $model2->delete(); // `EVENT_BEFORE_DELETE` will be trigerred
    // Something else
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.