博客列表 >Lavel-Event(laravel-事件系统)

Lavel-Event(laravel-事件系统)

冷雨画桥
冷雨画桥原创
2020年06月02日 16:53:431495浏览

先使用命令行生成一个事件文件

  1. php artisan make:event TestEvent

文件内容如下:

  1. <?php
  2. namespace App\Events;
  3. use Illuminate\Broadcasting\Channel;
  4. use Illuminate\Queue\SerializesModels;
  5. use Illuminate\Broadcasting\PrivateChannel;
  6. use Illuminate\Broadcasting\PresenceChannel;
  7. use Illuminate\Foundation\Events\Dispatchable;
  8. use Illuminate\Broadcasting\InteractsWithSockets;
  9. use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
  10. class TestEvent
  11. {
  12. use Dispatchable, InteractsWithSockets, SerializesModels;
  13. /**
  14. * Create a new event instance.
  15. *
  16. * @return void
  17. */
  18. public function __construct($data = [])
  19. {
  20. $this->data = $data;
  21. }
  22. /**
  23. * Get the channels the event should broadcast on.
  24. *
  25. * @return \Illuminate\Broadcasting\Channel|array
  26. */
  27. public function broadcastOn()
  28. {
  29. return new PrivateChannel('channel-name');
  30. }
  31. }

然后在App/Providers/EventServiceProvider 下定义事件和监听器

  1. protected $listen = [
  2. 'App\Events\TestEvent' => [
  3. 'App\Listeners\TestListener',
  4. ],
  5. ];

执行php artisan event:generate 生成监听器

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\TestEvent;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class TestListener
  7. {
  8. /**
  9. * Create the event listener.
  10. *
  11. * @return void
  12. */
  13. public function __construct()
  14. {
  15. //
  16. }
  17. /**
  18. * Handle the event.
  19. *
  20. * @param TestEvent $event
  21. * @return void
  22. */
  23. public function handle(TestEvent $event)
  24. {
  25. //
  26. }
  27. }

控制器中写入

  1. event(new TestEvent());
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议