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!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
