基于laravel5.6 功能需求:如当用户下单时,后台推送消息给管理员

一、注册Pusher

https://pusher.com/
注册完之后创建channels,获取app_id、key、secret、cluster;

二、配置Pusher

1、安装Pusher

  1. composer require pusher/pusher-php-server

2、配置env、config/broadcasting.php

  1. BROADCAST_DRIVER=pusher
  2. PUSHER_APP_ID=your-app-id
  3. PUSHER_APP_KEY=your-app-key
  4. PUSHER_APP_SECRET=your-app-secret
  5. PUSHER_APP_CLUSTER=your-app-cluster
  1. <?php
  2. 'pusher' => [
  3. 'driver' => 'pusher',
  4. 'key' => env('PUSHER_APP_KEY'),
  5. 'secret' => env('PUSHER_APP_SECRET'),
  6. 'app_id' => env('PUSHER_APP_ID'),
  7. 'options' => [
  8. 'cluster' => env('PUSHER_APP_CLUSTER'),
  9. 'encrypted' => true,
  10. 'curl_options' => [
  11. CURLOPT_SSL_VERIFYHOST => 0,
  12. CURLOPT_SSL_VERIFYPEER => 0,
  13. ]
  14. ],
  15. ],

三、建立事件

  1. php artisan make:event test

1、修改app/events/test.php

  1. <?php
  2. namespace App\Events;
  3. use App\Events\Event;
  4. use Illuminate\Queue\SerializesModels;
  5. use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
  6. class PusherEvent extends Event implements ShouldBroadcast
  7. {
  8. use SerializesModels;
  9. public $info;
  10. /**
  11. * PusherEvent constructor.
  12. */
  13. public function __construct($info)
  14. {
  15. $this->info = $info;
  16. }
  17. /**
  18. * 指定广播频道(对应前端的频道)
  19. * Get the channels the event should be broadcast on.
  20. *
  21. * @return array
  22. */
  23. public function broadcastOn()
  24. {
  25. return ['my-channel'];
  26. }
  27. /**
  28. * 指定广播事件(对应前端的事件)
  29. * @return string
  30. */
  31. public function broadcastAs()
  32. {
  33. return 'my-event';
  34. }
  35. /**
  36. * 获取广播数据,默认是广播的public属性的数据
  37. */
  38. public function broadcastWith()
  39. {
  40. return ['info' => $this->info];
  41. }
  42. }

2、注册事件监听器(app/providers/eventserviceprovider)

  1. protected $listen = [
  2. 'App\Events\Event' => [
  3. 'App\Listeners\EventListener',
  4. ],
  5. 'App\Events\Test' => [
  6. 'App\Listeners\SendTestInfo',
  7. ],
  8. ];

3、触发事件

在需要触发的地方调用该通知事件

  1. event(new Test('test-info'));

四、前端监听

  1. <script type="text/javascript" src="https://js.pusher.com/4.0/pusher.min.js"></script>
  2. <script>
  3. Pusher.logToConsole = true;
  4. var pusher = new Pusher("{{env("MIX_PUSHER_APP_KEY")}}", {
  5. cluster: '{{env('MIX_PUSHER_APP_CLUSTER')}}',
  6. encrypted: true
  7. });
  8. var channel = pusher.subscribe('my-channel'); //频道
  9. channel.bind('my-event', function(data) { //事件名
  10. console.log(data.info);
  11. });
  12. </script>