本文目录导读:

- 在 EventServiceProvider 中注册(推荐)
- 使用 artisan 命令生成并注册
- 在路由或控制器中动态注册
- 使用通配符监听器
- 队列化监听器
- 事件订阅者
- 自动发现事件(Laravel 8.57+)
- 注意事项
在 Laravel 中注册事件监听器主要有以下几种方式:
在 EventServiceProvider 中注册(推荐)
这是最常用的方式,在 app/Providers/EventServiceProvider.php 中:
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use App\Events\OrderShipped;
use App\Listeners\SendShipmentNotification;
class EventServiceProvider extends ServiceProvider
{
/**
* 事件与监听器的映射
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
OrderShipped::class => [
SendShipmentNotification::class,
],
];
/**
* 注册任何其他事件
*/
public function boot()
{
parent::boot();
// 使用闭包注册
Event::listen('event.name', function ($data) {
// 处理逻辑
});
}
}
使用 artisan 命令生成并注册
创建事件和监听器:
# 创建事件 php artisan make:event OrderShipped # 创建监听器 php artisan make:listener SendShipmentNotification --event=OrderShipped # 自动在 EventServiceProvider 注册
在路由或控制器中动态注册
use Illuminate\Support\Facades\Event;
// 在任何地方注册
Event::listen('App\Events\OrderShipped', function ($event) {
// 处理事件
});
// 或者在控制器中
public function registerEvent()
{
Event::listen('order.shipped', function ($order) {
Log::info('Order shipped: ' . $order->id);
});
}
使用通配符监听器
// 在 EventServiceProvider 的 boot 方法中
public function boot()
{
parent::boot();
// 监听所有 App\Events 命名空间下的事件
Event::listen('App\Events\*', function ($eventName, $data) {
Log::info("Event {$eventName} fired");
});
}
队列化监听器
如果需要异步处理,可以实现 ShouldQueue 接口:
<?php
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendShipmentNotification implements ShouldQueue
{
public function handle($event)
{
// 异步处理逻辑
}
}
事件订阅者
创建订阅者类:
<?php
namespace App\Listeners;
class UserEventSubscriber
{
public function handleUserLogin($event)
{
// 处理登录事件
}
public function handleUserLogout($event)
{
// 处理登出事件
}
public function subscribe($events)
{
$events->listen(
'Illuminate\Auth\Events\Login',
[UserEventSubscriber::class, 'handleUserLogin']
);
$events->listen(
'Illuminate\Auth\Events\Logout',
[UserEventSubscriber::class, 'handleUserLogout']
);
}
}
在 EventServiceProvider 中注册订阅者:
protected $subscribe = [
UserEventSubscriber::class,
];
自动发现事件(Laravel 8.57+)
在 EventServiceProvider 中启用:
public function shouldDiscoverEvents()
{
return true;
}
Laravel 会自动扫描并注册事件和监听器。
注意事项
- 执行顺序:多个监听器按注册顺序执行
- 事件优先级:可以通过
$listenerPriority属性设置优先级 - 缓存事件:生产环境可以缓存事件注册
php artisan event:cache php artisan event:clear # 清除缓存
选择哪种方式取决于你的具体需求,对于大多数项目,使用 EventServiceProvider 的 $listen 数组是最简单和推荐的方式。