Home >Backend Development >PHP Tutorial >Custom Events in Laravel

Custom Events in Laravel

William Shakespeare
William ShakespeareOriginal
2025-03-04 09:07:10116browse

Custom Events in Laravel

In this article, we are going to explore the basics of event management in Laravel. We'll also create a real-world example of a custom event and listener.

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

For example, let's 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 an 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, which 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.

Go ahead and pull in the app/Providers/EventServiceProvider.php file.

<?php<br><br>namespace App\Providers;<br><br>use Illuminate\Auth\Events\Registered;<br>use Illuminate\Auth\Listeners\SendEmailVerificationNotification;<br>use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;<br>use Illuminate\Support\Facades\Event;<br><br>class EventServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * The event listener mappings for the application.<br>     *<br>     * @var array<br>     */<br>    protected $listen = [<br>        Registered::class => [<br>            SendEmailVerificationNotification::class,<br>        ],<br>    ];<br><br>    /**<br>     * Register any events for your application.<br>     *<br>     * @return void<br>     */<br>    public function boot()<br>    {<br>        parent::boot();<br><br>        //<br>    }<br>}<br>

Let's have a close look at the login event.

Of course, you need to define the artisan command.

php artisan event:generate<br>

This command generates event and listener classes listed under the artisan command to generate a base template code.

php artisan event:generate<br>

That should have created the event class at app/Events/ClearCache.php and the listener class at app/Listeners/WarmUpCache.php.

With a few changes, the app/Events/ClearCache.php class should look like this:

<?php<br><br>namespace App\Events;<br><br>use Illuminate\Broadcasting\Channel;<br>use Illuminate\Broadcasting\InteractsWithSockets;<br>use Illuminate\Broadcasting\PresenceChannel;<br>use Illuminate\Broadcasting\PrivateChannel;<br>use Illuminate\Contracts\Broadcasting\ShouldBroadcast;<br>use Illuminate\Foundation\Events\Dispatchable;<br>use Illuminate\Queue\SerializesModels;<br><br>class ClearCache<br>{<br>    use Dispatchable, InteractsWithSockets, SerializesModels;<br><br>    public $cache_keys = [];<br><br>    /**<br>     * Create a new event instance.<br>     *<br>     * @return void<br>     */<br>    public function __construct(Array $cache_keys)<br>    {<br>        $this->cache_keys = $cache_keys;<br>    }<br><br>    /**<br>     * Get the channels the event should broadcast on.<br>     *<br>     * @return \Illuminate\Broadcasting\Channel|array<br>     */<br>    public function broadcastOn()<br>    {<br>        return new PrivateChannel('channel-name');<br>    }<br>}<br>

As you've probably noticed, we've added a new property 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<code>AppListenersWarmUpCache listener is set to listen to the AppEventsClearCache<code>AppEventsClearCache event. Thus, the handle<code>handle method of the AppListenersWarmUpCache<code>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 to 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.

<?php<br><br>namespace App\Providers;<br><br>use Illuminate\Auth\Events\Registered;<br>use Illuminate\Auth\Listeners\SendEmailVerificationNotification;<br>use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;<br>use Illuminate\Support\Facades\Event;<br><br>class EventServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * The event listener mappings for the application.<br>     *<br>     * @var array<br>     */<br>    protected $listen = [<br>        Registered::class => [<br>            SendEmailVerificationNotification::class,<br>        ],<br>    ];<br><br>    /**<br>     * Register any events for your application.<br>     *<br>     * @return void<br>     */<br>    public function boot()<br>    {<br>        parent::boot();<br><br>        //<br>    }<br>}<br>

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

The first argument of the listen method is an event which you want to listen to, and the second argument is a listener which 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 $subscribe property, as shown in the following snippet.

php artisan event:generate<br>

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 exciting features of Laravel—events and listeners. They're based on the observer design pattern, which allows you to raise application-wide events and allow other modules to listen to those events and react accordingly.

The above is the detailed content of Custom Events in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn