Working with Yii2 Events

Hi, recently I’ve been refactoring a Yii2 project to meet my clients changing needs and part of it was to send an email to subscribers after bulk uploading new records only. The current solution uses a cron job which is very limiting as subscribers can only wait for the next day to receive updates as per the cron schedule.

Previously, I used the ActiveRecord methods like beforeSave() and afterSave(), but these are also limiting for this scenario because my custom event will be run on saving each record. For example, if one excel import has 1k records, then the subscribers will receive 1k emails….thus not ideal.

The ideal way Yii2 class level events came in handy for this scenario and below is a step by step on how I handled it. Step 1: Create a constant that will identify the event in your ActiveRecord class.

Step 2: Attach the event handler in the init method of your ActiveRecord. An event handler is a PHP callback that gets executed when the event it is attached to is triggered. In this case, sendMail handler is a Records object method.

Step 3: Add sendMail method to ActiveRecord class.

Step 4: Trigger the event We’ve got everything and we can now trigger the event from any part of the application.

That's it guys hope by now you’ve got the idea of how you can implement events in your Yii2 web app.

No Comments Yet