Difference between afterSave and event in yii2?

I wanted to send an email to the administrator when a new user is registered. I think I can do this in two ways. one way is to use events, and the other is to use afterSave. Using Controller Code Events

 public function actionCreate()
    {
        $model = new Registeration();

        if ($model->load(Yii::$app->request->post())) 
        {
            if($model->save())
            {
                $model->trigger(Registeration::EVENT_NEW_USER); 
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

Model code

const EVENT_NEW_USER = 'new-user'; 
public function init(){

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

}

public function sendMail($event){
   //  code 
}

I can do the same with the method afterSave

Model code

public function afterSave($insert)
{
   //code
    return parent::afterSave($insert);
}

So is there a difference between the two methods? Which one is better to use Eventsor afterSave()?

+4
source share
1 answer

I'm new to Yii,

It depends on what you are trying to implement.

If you use postSave, an email will also be sent for updates.

, .

+4

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


All Articles