Home>Article>PHP Framework> Detailed example of Laravel event monitoring
This article brings you relevant knowledge aboutlaravel, which mainly introduces related issues about event monitoring. The steps to implement event monitoring are to create events, create listeners, bind events and Listen and trigger events. Let's take a look at the example below. I hope it will be helpful to everyone.
[Related recommendations:laravel video tutorial]
Laravel Event & Listener event listening mechanism allows developers to not only Code is a way to organize the code in a more orderly manner, and it is also a highly abstract mapping of the operating rules of real society. Our real society is also like this. We monitor changes in things and respond to changes, so that things develop according to our wishes. Anticipated development. When reality is mapped into code logic, events and their processing logic are usually separated. After all, not all events need to be responded to immediately. Combined with queues, we can make the workflow of event monitoring and processing more perfect.
Monitor log file size changes
User login: record user login times and record access related information
1. Create event: event
2. Create listener: listener
3. Bind events and listener
4. Trigger event
1. Create login event: event
app/Events/UserLogin.php
php artisan make:event UserLogin//获取用户信息实例 public function __construct(User $user){ $this->user = $user;}
2. Create user Login email is sent to monitor, and the UserLogin login event is bound at the same time: listener
app/Listeners/EmailAdminUserLogin.php
php artisan make:listener EmailAdminUserLogin --event=UserLogin //日志打印登录用户信息public function handle(UserLogin $event) {// dd($event); //日志打印登录用户信息 Log::info($event->user->name . '已经登录'); }
3. Registration event and listening binding relationship
One event can correspond to multiple listeners
app/Providers/EventServiceProvider.php
protected $listen = [ 'App\Events\UserLogin' => [ 'App\Listeners\EmailAdminUserLogin', ],];
4. Trigger the event when the user logs in
app/Http/Controllers/Auth/LoginController.php
//覆写AuthenticatesUsers类的authenticated方法protected function authenticated(Request $request, $user){ //触发事件 event(new UserLogin($user));}
Here will generate corresponding events and monitors based on the attribute listen in app/Providers/EventServiceProvider.php
php artisan event:generate
[Related recommendations:laravel video tutorial】
The above is the detailed content of Detailed example of Laravel event monitoring. For more information, please follow other related articles on the PHP Chinese website!