laravel event事件 讲解

本文详细介绍如何在Laravel框架中使用事件总线,包括事件的注册与触发、监听器的实现、事件合集及队列化事件的使用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

event
注册简单event
首先在 EventServiceProvider中的属性$listen添加事件和监听
  protected $listen = [
        'App\Events\openEvent' => [//事件
            'App\Listeners\openListener',//监听器
        ],
    ];
    执行php artisan event:generate
    会生成 events/App\Events\openEvent.php 和Listeners/App\Listeners\openListener
    在events/App\Events\openEvent.php
    中添加
    public function __construct($show)
    {
        $this->show = $show;
    }
    则此时的 events属性show 就是 事件标识

    在Listeners/App\Listeners\openListener 下的
    public function handle(openEvent $event)
    {
       
    }
    此event 就是事件对象,$event->show 就是我们的事件标识

    在控制器方法中使用
    use App\Events\showEvent;
   use Event;


    Event::fire(new showEvent('事件标识'));或者全局函数
    event(new showEvent('事件标识'));

    此时监听器就会自动执行并根据事件的标识执行不同的操作

    2. 手动定义事件
    在 providers/EventServiceProvider.php
    public function boot()
    {
        parent::boot($events);
        Event::listen('event.show', function($listen){// 如果定义的是单个事件,闭包接受一个参数,
如果十多个event.*必报两个参数
            dd($listen);
    });
ps event.show 是我们定义的事件标识 闭包参数使我们传递的事件数据

党控制器调用Event::fire('event.show',['show1']);时  则会执行
providers/EventServiceProvider.php 相对应的事件 并把第二个参数传到 闭包函数

    在控制器中执行 Event::fire('event.show',['show1']);

    3. 为防止事件堵塞程序 ,使用队列列化的事件 只需要使监听器实现ShouldQueue 接口
    namespace App\Listeners;

   use App\Events\showEvent;
   use Illuminate\Queue\InteractsWithQueue;
   use Illuminate\Contracts\Queue\ShouldQueue;

   class showListener implements ShouldQueue

    4.事件的合集 事件订阅器

    在EventServiceProvider中添加

    protected $subscribe = [
        'App\Listeners\subscribetListener',//注册事件订阅器
    ];


    事件订阅器实现
namespace App\Listeners;


class subscrListener
{
    /**
     * 处理用户登录事件。
     */
    public function onUserLogin($event) {

    }

    /**
     * 处理用户注销事件。
     */
    public function onUserLogout($event) {

    }

    /**
     * 注册侦听器的订阅者。
     *
     * @param  Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'App\Events\UserLoggedIn',
            'App\Listeners\subscrListener@onUserLogin'//UserLoggedIn 事件的监听者是 onUserLogin 方法
        );

        $events->listen(
            'App\Events\UserLoggedOut',
            'App\Listeners\subscrListener@onUserLogout'//UserLoggedOut 事件的监听者是 onUserLogout 方法
        );
    }

}


控制器调用
        Event::fire(new UserLoggedIn('UserLoggedIn'));
       
        Event::fire(new UserLoggedOut('UserLoggedOut'));





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值