How to use events in yii2?

I can explain events by a simple example. Let’s say, you want to do few things when a user first registers to the site like:

  1. Send an email to the admin.
  2. Create a notification.
  3. you name it.

You may try to call a few methods after a user object is successfully saved. Maybe like this:

if($model->save()){
   $mailObj->sendNewUserMail($model);
   $notification->setNotification($model);
}

So far it may seem fine but what if the number of requirements grows with time? Say 10 things must happen after a user registers himself? Events come handy in situations like this.

Basics of events

Events are composed of the following cycle.

  1. You define an event. Say, new user registration.
  2. You name it in your model. Maybe adding constant in User model. Like const EVENT_NEW_USER='new_user';. This is used to add handlers and to trigger an event.
  3. You define a method that should do something when an event occurs. Sending an email to Admin for example. It must have an $event parameter. We call this method a handler.
  4. You attach that handler to the model using its a method called on(). You can call this method many times you wish – simply you can attach more than one handler to a single event.
  5. You trigger the event by using trigger().

Note that, all the methods mentioned above are part of Component class. Almost all classes in Yii2 have inherited form this class. Yes ActiveRecord too.

Let’s code

To solve above mentioned problem we may have User.php model. I’ll not write all the code here.

// in User.php i've declared constant that stores event name
const EVENT_NEW_USER = 'new-user';

// say, whenever new user registers, below method will send an email.
public function sendMail($event){
   echo 'mail sent to admin';
   // you code 
}

// one more hanlder.

public function notification($event){
  echo 'notification created';
}

One thing to remember here is that you’re not bound to create methods in the class that creates an event. You can add any static, non static method from any class.

I need to attach above handlers to the event . The basic way I did is to use AR’s init() method. So here is how:

// this should be inside User.php class.
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.
}

The final thing is to trigger an event. Now you don’t need to explicitly call all the required methods as we did before. You can replace it by following:

if($model->save()){
  $model->trigger(User::EVENT_NEW_USER); 
}

All the handlers will be automatically called.

Leave a Comment