5

I wanted to send an email to admin when a new user registers. I think i can do it using two ways. one way is to use events and other is by using afterSave. By using Events Controller code

 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 using the afterSave method

Model code

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

So is there any difference between the two methods? Which one is better using Events or afterSave() ?

Bloodhound
  • 2,906
  • 11
  • 37
  • 71
  • 2
    from your code your Registeration Event would be called after the afterSave event ;) but the coding style with the additional event handling is better, because you could extend from your Model class without attaching the event. – BHoft Oct 19 '15 at 09:23
  • @BHoft yes Registeration event would be called after $model->save(); is that an error from my part plz explain – Bloodhound Oct 19 '15 at 09:28
  • 2
    no both is "right" but your additional event is better coding style for future purposes. So adding a new Event is the better solution. – BHoft Oct 19 '15 at 09:35
  • I'd go with `afterSave` in your model. Events are better suited for situations when you don't extend the original class, and just want something to happen at a specific point. – Beowulfenator Oct 20 '15 at 10:07
  • @Beowulfenator can you write it as an answer? – Bloodhound Oct 20 '15 at 11:56

1 Answers1

4

I am new to Yii,

It depends on what you are trying to implement.

When you use afterSave email will be sent on updates also.

So event would be a better choice to your problem.

Thanks & Regards

Paul P Elias

Paul P Elias
  • 146
  • 2
  • 7
  • $insert - If false, it means the method is called while updating a record. From the [Official doc](http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#afterSave()-detail) – musafar006 Dec 20 '16 at 05:40