ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
### 1: 生成事件和监听器 可以使用`make:event`以及`make:listener`用于生成单个事件和监听器的 Artisan 命令 #### 事件 ``` php artisan make:event SysNotifyEvent ``` #### 监听器 ``` php artisan make:listener SysNotifyListener --event=SysNotifyEvent ``` ### 2: 手动注册事件 通常,事件应该通过 EventServiceProvider $listen 数组注册;但是,你也可以在 EventServiceProvider 的 boot 方法中手动注册基于类或闭包的事件监听器: ~~~ public function boot(): void { Event::listen( SysNotifyEvent::class, [SysNotifyListener::class, 'handle'] ); } ~~~ 或者 ~~~ protected $listen = [ SysNotifyEvent::class => [ SysNotifyListener::class ], ]; ~~~ ### 3:定义事件 ~~~ namespace App\Events; class SysNotifyEvent { public function __construct(public $to_user_id = null, public $content = '') { } } ~~~ ### 4:定义监听器 ~~~ <?php namespace App\Listeners; use App\Events\SysNotifyEvent; use App\Models\UserJobNotifaction; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; class SysNotifyListener { public function handle(SysNotifyEvent $event): void { UserJobNotifaction::create([ 'user_id' => UserJobNotifaction::SYS_NOTIFY_TYPE_NUMBER, 'to_user_id' => $event->to_user_id, 'content' => $event->content, 'type' => 'text', 'input_time' => getSystime() ]); } } ~~~ 如果使用队列继承ShouldQueue类 ~~~ class SysNotifyListener implements ShouldQueue ~~~ > 如果你的监听器要执行一个缓慢的任务,如发送电子邮件或进行 HTTP 请求,那么队列化监听器就很有用了。在使用队列监听器之前,请确保 配置你的队列 并在你的服务器或本地开发环境中启动一个队列 worker。 ### 5:使用方法 ~~~ SysNotifyEvent::dispatch($user_id, 'بۇ بىر سىناق ئۇقتۇرۇش'); ~~~