先使用命令行生成一个事件文件
php artisan make:event TestEvent
文件内容如下:
<?phpnamespace App\Events;use Illuminate\Broadcasting\Channel;use Illuminate\Queue\SerializesModels;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Broadcasting\PresenceChannel;use Illuminate\Foundation\Events\Dispatchable;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;class TestEvent{use Dispatchable, InteractsWithSockets, SerializesModels;/*** Create a new event instance.** @return void*/public function __construct($data = []){$this->data = $data;}/*** Get the channels the event should broadcast on.** @return \Illuminate\Broadcasting\Channel|array*/public function broadcastOn(){return new PrivateChannel('channel-name');}}
然后在App/Providers/EventServiceProvider 下定义事件和监听器
protected $listen = ['App\Events\TestEvent' => ['App\Listeners\TestListener',],];
执行php artisan event:generate 生成监听器
<?phpnamespace App\Listeners;use App\Events\TestEvent;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Contracts\Queue\ShouldQueue;class TestListener{/*** Create the event listener.** @return void*/public function __construct(){//}/*** Handle the event.** @param TestEvent $event* @return void*/public function handle(TestEvent $event){//}}
控制器中写入
event(new TestEvent());
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号