Yii2 events | How events work?

How events work?

Events are similar to social media notifications. When the person you follow publishes a new post, you will receive a notification. Because you are subscribed to certain actions.

Here's a real-life analogy: Let's say you and a friend decide to go to the movies. You agreed to meet at the entrance of the cinema. You asked a friend to call you when he arrives at the meeting point. So your friend's "Arrival at the meeting point" is an EVENT. You subscribed to this event and gave instructions to a friend (to do certain actions, that is, to call you) when an event will happen.

In Yii2, by default, there are several events that will happen at specific times. For example, after connecting to the database, before saving data to the database, authorization-related events, query-level events, etc., etc.

If you subscribe to an event that will occur before saving data to the database, then before saving data in the database the execution of your instructions will begin automatically.

In the code below, we are subscribing to the EVENT_AFTER_ACTION event of the current controller. Here, the handler is an anonymous function.

Also, instead of an anonymous function, you can use:


What are events for?

In short, events are needed to inject your code into third-party code without changing the third-party code.

Events help create a loosely coupled system. That is, if several people are working on the project, for example, the one who writes the module for registration will add several events to his code. He does not have to know what will happen after the user is registered. And the programmer who writes the SMS notification module can subscribe to the events of the registration module. And then, after registering the user, an SMS will be automatically sent to the administrator, user, etc., etc.


When should you use events?

Events should be used:

  • if the project is developed by several people.
  • if you write a library.
  • if you are writing a loosely coupled, independent of each other modular system.


Below are the built in yii2 events.

Comments