25. Laravel 事件

Laravel 事件

配套视频地址:https://www.bilibili.com/video/av77534496

目的:解耦。

简介:监听器监听到事件的发生,会执行 handler 方法。

// 原始代码
public function register(){
    // 注册用户
    // 成功后发送欢迎的信息通知
}


// 事件解耦后
public function register(){
    // 注册用户
    event('App\Events\RegisterOk');
}

注册事件和监听器

# EventServiceProvider 
protected $listen = [
    'App\Events\OrderShipped' => [
        'App\Listeners\SendShipmentNotification',
    ],
];


# 在 boot 方法里,以闭包方式注册

//触发事件调用
event('event.name', $user);
//以下放boot方法里
Event::listen('event.name', function ($user) {

});
# 通配符
Event::listen('event.*', function ($eventName, array $data) {
    //
});



// 配置自动发现后可以不注册了,Laravel 会自动扫描目录。
# EventServiceProvider
public function shouldDiscoverEvents()
{
    return true;
}
// 配置自动扫描的目录
protected function discoverEventsWithin()
{
    return [
        $this->app->path('Listeners'),
    ];
}
php artisan event:generate
// 避免手动建立事件类、监听器类,根据你在 
`EventServiceProvider` 里 `$listen` 自动生成
// 生产环境避免每次请求扫描目录
php artisan event:cache
php artisan event:clear

定义事件

<?php

namespace App\Events;

use App\Order;
use Illuminate\Queue\SerializesModels;

class OrderShipped
{
    use SerializesModels;

    public $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }
}

定义监听器

<?php

namespace App\Listeners;

use App\Events\OrderShipped;

class SendShipmentNotification
{
    public function __construct()
    {
        //
    }

    public function handle(OrderShipped $event)
    {
        // Access the order using $event->order...
        // 想禁止冒泡,请 return false
    }
}

分发事件

$order = Order::findOrFail($orderId);
event(new OrderShipped($order));

事件订阅器

实现了在单个类中包含多个监听器。

<?php

namespace App\Listeners;

class UserEventSubscriber
{
    /**
     * Handle user login events.
     */
    public function handleUserLogin($event) {}

    /**
     * Handle user logout events.
     */
    public function handleUserLogout($event) {}

    /**
     * Register the listeners for the subscriber.
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'Illuminate\Auth\Events\Login',
            'App\Listeners\UserEventSubscriber@handleUserLogin'
        );

        $events->listen(
            'Illuminate\Auth\Events\Logout',
            'App\Listeners\UserEventSubscriber@handleUserLogout'
        );
    }
}

注册事件订阅器

# EventServiceProvider  
protected $subscribe = [
    'App\Listeners\UserEventSubscriber',
];

posted on   何苦->  阅读(56)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示