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'));
laravel event事件 讲解
最新推荐文章于 2024-07-06 04:45:22 发布