Event and Listener in Laravel

Tram Ho

1. What is Event?

An event is an event, an action that occurs in the system at a specified time. Events can be generated by user actions or generated internally within the system. The application of events in programming is huge, not only Laravel but many other PHP frameworks, more broadly, other programming languages ​​use events. Event allows us to insert another handler into the current code at certain points. You can attach custom snippets to an event, so that when the event is fired, the code above will be executed automatically. This code is the listener: objects that will be called for handling when the event is fired.

A simple example would be to send a new member welcome email every time a user successfully registers an account. Under the logic of code, when the successful registration event is triggered, the system will automatically send a welcome email for new members. The event here is the successful registration action, the Listener is the email object (the code is responsible for sending email to the user).

Event makes it possible to separate other handlers from the current logic bussiness without affecting the current handler. An event can be handled by many different handler classes and completely separate.

In Laravel, event classes will be placed in app / Events, and listening classes are placed in app / Listeners.

Laravel provides many different ways to implement Event & Listener, but it only revolves around 4 main points, grasping these 4 points, we are completely free to deploy:

2. Register event & listener

It also declares which event will be listened to by which listener. Laravel provides two main ways to register event & listeners.

  • Register in EventServiceProvider

  • Manually register the event (using the helper or facede provided by Laravel)

There are also a number of other methods such as using event auto discovery, and event subscribers, too.

3. Declare the event

Registering a class that acts as a data container containing event information. This class has almost no logic, but only assigns the necessary information to the event. Create a new event using the command php artisan event:generate if we have declared the full $ listen array in the EventServiceProvider, or the command php artisan make:event Event

An example class PostViewedEvent to declare events when the post is viewed.

This is the event called each time the post is viewed to increase the number of views of the post (view_count), the class only implements the assignment of the $ post object that is viewed to the data of the event.

Note: here it is possible to assign an Eloquent Post model directly to the __construct function because of using trait SerializesModels. the model will be serialized and unserialized when the job is executed.

4. Declare listener

Listener is the class to handle events and perform logic processing. The listener receives an instance of the event object in the handle () function. Here we can access information of the object that generated the event. An example for the PostViewedListener event handler listener see the above post:

5. How to initiate an event

To fire an event, Larvel provides two methods: using the Event helper or the static method dispatch (the event needs to use the Dispatchable trait).

6. Queued Event Listeners

Laravel is essentially a step-by-step process, so having some heavy-duty and time-consuming tasks (sending email as an example) will still affect system performance. Then you will want to separate one thread from the other. Laravel has provided many solutions for that, Queued Event Listeners is an example.

The essence of this is that Laravel will push the event data into a queue for later processing, this queue can be stored in the database or redis and some other queue backend, you can configure it in config / queue.php. . This is similar to the job and task scheduling concepts that you will likely come across in Laravel.

To run listeners to handle these events, you need to set up the job listener system to run to handle the events:

Note that, when running this command, the processing code will be stored in memory, so when there is a change in the processing code, you need to restart the queue using the command:

For more details, see the Laravel docs .

7. Event Subscribers

Event subscriber is a class that allows you to subscribe to multiple event + handlers handled in the same class. Subscriber needs to have a subscribe method, and needs to be registered in the EventServiceProvider using the $ subscribe property :

And register in EventServiceProvider :

8. Broadcasting Event

Similar to the queued event, however, the way and purpose of broadcasting event is slightly different. Broadcasting events are often used for real-time purposes, to inform, update changes to the client. To do this, Laravel provides a simple way to broadcast events over a websocket connection. The front-end client side will use this websocket to receive the updated data from the server. On the client side, Laravel also provides a Laravel Echo package available to handle broadcast events. ( https://laravel.com/docs/7.x/broadcasting#receiving-broadcasts )

To use broadcast, in addition to having to configure the queue listener, you need to configure the backend for broadcast at config / broadcasting.php. Laravel supports several backend drivers like Pusher Channels, Redis and log (for testing locally). If you want to quit broadcasting completely, you just need to configure this broadcaster to null. As for why we have to configure the queue listener, Laravel designs all broadcast events to be queued in the processing queue so as not to affect the main system's processing.

To implement the broadcast event, we just need to implement the Illuminate Contracts Broadcasting ShouldBroadcast interface in the event class. This interface will require the class to have a broadcastOn method, which will return the channel on which the event will be broadcast.

9. Termination

So we have grasped the basics of events in Laravel as well as some more advanced techniques such as queued event, event broadcasts. Thank you for watching.

Share the news now

Source : Viblo