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!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
