Need to clarify events YII2

Trying to find out events in Yii 2. I found several resources. The link to which I received more attention is here.

How to use events in yii2?

In the first comment he explains an example. Let's say that we have 10 things that need to be done after registration - in this situation, the events are convenient.

Is calling this function a big deal? The same thing happens inside the init 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 can I get the full benefit of using them? Please note that this question is part of the Yii 2 training. Please explain an example. Thanks in advance.

+4
source share
1 answer

( ) , , . , .

, . (, ) . , ( : Only main administrator can create new users and main administrator cannot be deleted). .

User ( , User ), init() , 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!');
    }
}

, self::EVENT_BEFORE_DELETE, , , .

, :

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
}
+8

Source: https://habr.com/ru/post/1666067/


All Articles