博主信息
博文 7
粉丝 0
评论 0
访问量 17638
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
Lavel-Event(laravel-事件系统)
冷雨画桥
原创
1756人浏览过

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

  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举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学