Custom Events in Laravel

Custom Events in Laravel

In this article, we are going to explore the basics of event management in Laravel. It's one of the important features that you, as a developer, should have in your arsenal in your desired framework. As we move on, we'll also grab this opportunity to create a real-world example of a custom event and listener, and that's the ultimate goal of this article as well.

The concept of events in Laravel is based on a very popular software design pattern—the observer pattern. In this pattern, the system is supposed to raise events when something happens, and you could define listeners that listen to these events and react accordingly. It's a really useful feature in a way that allows you to decouple components in a system that otherwise would have resulted in tightly coupled code.

For example, say you want to notify all modules in a system when someone logs into your site. Thus, it allows them to react to this login event, whether it's about sending an email or in-app notification or for that matter anything that wants to react to this login event.

Basics of Events and Listeners

In this section, we'll explore Laravel's way of implementing events and listeners in the core framework. If you're familiar with the architecture of Laravel, you probably know that Laravel implements the concept of a service provider that allows you to inject different services into an application.

Similarly, Laravel provides a built-in EventServiceProvider.php class that allows us to define event listener mappings for an application.

Let's have a close look at the $listen property, which allows you to define an array of events and associated listeners. The array keys correspond to events in a system, and their values correspond to listeners that will be triggered when the corresponding event is raised in a system.

I prefer to go through a real-world example to demonstrate it further. As you probably know, Laravel provides a built-in authentication system that facilitates features like login, register, and the like.

Assume that you want to send the email notification, as a security measure, when someone logs into the application. If Laravel didn't support the event listener feature, you might have ended up editing the core class or some other way to plug in your code that sends an email.

In fact, you're on the luckier side as Laravel helps you to solve this problem using the event listener. Let's revise the app/Providers/EventServiceProvider.php file to look like the following.

IlluminateAuthEventsLogin is an event that'll be raised by the Auth plugin when someone logs into an application. We've bound that event to the AppListenersSendEmailNotification listener, so it'll be triggered on the login event.

Of course, you need to define the AppListenersSendEmailNotification listener class in the first place. As always, Laravel allows you to create a template code of a listener using the artisan command.

php artisan event:generate

This command generates event and listener classes listed under the $listen property.

In our case, the IlluminateAuthEventsLogin event already exists, so it only creates the AppListenersSendEmailNotification listener class. In fact, it would have created the IlluminateAuthEventsLogin event class too if it didn't exist in the first place.

Let's have a look at the listener class created at app/Listeners/SendEmailNotification.php.

It's the handle method that will be invoked with appropriate dependencies whenever the listener is triggered. In our case, the $event argument should contain contextual information about the login event—logged in user information.

And we can use the $event object to carry out further processing in the handle method. In our case, we want to send the email notification to the logged in user.

So that's how you're supposed to use the events feature in Laravel. From the next section onwards, we'll go ahead and create a custom event and associated listener class.

Create a Custom Event

The example scenario that we're going to use for our example is something like this:

An application needs to clear caches in a system at certain points. We'll raise the CacheClear event along with the contextual information when an application does the aforementioned. We'll pass cache group keys along with an event that was cleared.

Other modules in a system may listen to the CacheClear event and would like to implement code that warms up related caches.

When the listener is invoked, the handle method is passed with the instance of the associated event. In our case, it should be the instance of the ClearCache event that will be passed as the first argument to the handle method.

Next, it's just a matter of iterating through each cache key and warming up associated caches.

Now, we have everything in place to test things against. Let's quickly create a controller file at app/Http/Controllers/EventController.php to demonstrate how you could raise an event.

Firstly, we've passed an array of cache keys as the first argument while creating an instance of the ClearCache event.

The event helper function is used to raise an event from anywhere within an application. When the event is raised, Laravel calls all listeners listening to that particular event.

In our case, the AppListenersWarmUpCache listener is set to listen to the AppEventsClearCache event. Thus, the handle method of the AppListenersWarmUpCache listener is invoked when the event is raised from a controller. The rest is to warm up caches that were cleared!

So that's how you can create custom events in your application and work with them.

What Is an Event Subscriber?

The event subscriber allows you to subscribe multiple event listeners in a single place. Whether you want to logically group event listeners or you want to contain growing events in a single place, it's the event subscriber you're looking for.

If we had implemented the examples discussed so far in this article using the event subscriber, it might look like this.

It's the subscribe method that is responsible for registering listeners. The first argument of the subscribe method is the instance of the IlluminateEventsDispatcher class that you could use to bind events with listeners using the listen method.

The first argument of the listen method is an event that you want to listen to, and the second argument is a listener that will be called when the event is raised.

In this way, you can define multiple events and listeners in the subscriber class itself.

The event subscriber class won't be picked up automatically. You need to register it in the EventServiceProvider.php class under the $subscriber property, as shown in the following snippet.

So that was the event subscriber class at your disposal, and with that we've reached the end of this article as well.

Conclusion

Today we've discussed a couple of the exciting features of Laravel—events and listeners. They're based on the observer design pattern that allows you to raise application-wide events and allow other modules to listen to those events and react accordingly.

Just getting up to speed in Laravel or looking to expand your knowledge, site, or application with extensions? We have a variety of things you can study in Envato Market.