Laravel事件监听器怎么注册

wen PHP项目 1

本文目录导读:

Laravel事件监听器怎么注册

  1. 在 EventServiceProvider 中注册(推荐)
  2. 使用 artisan 命令生成并注册
  3. 在路由或控制器中动态注册
  4. 使用通配符监听器
  5. 队列化监听器
  6. 事件订阅者
  7. 自动发现事件(Laravel 8.57+)
  8. 注意事项

在 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 会自动扫描并注册事件和监听器。

注意事项

  1. 执行顺序:多个监听器按注册顺序执行
  2. 事件优先级:可以通过 $listenerPriority 属性设置优先级
  3. 缓存事件:生产环境可以缓存事件注册
php artisan event:cache
php artisan event:clear  # 清除缓存

选择哪种方式取决于你的具体需求,对于大多数项目,使用 EventServiceProvider$listen 数组是最简单和推荐的方式。

抱歉,评论功能暂时关闭!