基于laravel5.6 功能需求:如当用户下单时,后台推送消息给管理员
一、注册Pusher
https://pusher.com/
注册完之后创建channels,获取app_id、key、secret、cluster;
二、配置Pusher
1、安装Pusher
composer require pusher/pusher-php-server
2、配置env、config/broadcasting.php
BROADCAST_DRIVER=pusherPUSHER_APP_ID=your-app-idPUSHER_APP_KEY=your-app-keyPUSHER_APP_SECRET=your-app-secretPUSHER_APP_CLUSTER=your-app-cluster
<?php'pusher' => ['driver' => 'pusher','key' => env('PUSHER_APP_KEY'),'secret' => env('PUSHER_APP_SECRET'),'app_id' => env('PUSHER_APP_ID'),'options' => ['cluster' => env('PUSHER_APP_CLUSTER'),'encrypted' => true,'curl_options' => [CURLOPT_SSL_VERIFYHOST => 0,CURLOPT_SSL_VERIFYPEER => 0,]],],
三、建立事件
php artisan make:event test
1、修改app/events/test.php
<?phpnamespace App\Events;use App\Events\Event;use Illuminate\Queue\SerializesModels;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;class PusherEvent extends Event implements ShouldBroadcast{use SerializesModels;public $info;/*** PusherEvent constructor.*/public function __construct($info){$this->info = $info;}/*** 指定广播频道(对应前端的频道)* Get the channels the event should be broadcast on.** @return array*/public function broadcastOn(){return ['my-channel'];}/*** 指定广播事件(对应前端的事件)* @return string*/public function broadcastAs(){return 'my-event';}/*** 获取广播数据,默认是广播的public属性的数据*/public function broadcastWith(){return ['info' => $this->info];}}
2、注册事件监听器(app/providers/eventserviceprovider)
protected $listen = ['App\Events\Event' => ['App\Listeners\EventListener',],'App\Events\Test' => ['App\Listeners\SendTestInfo',],];
3、触发事件
在需要触发的地方调用该通知事件
event(new Test('test-info'));
四、前端监听
<script type="text/javascript" src="https://js.pusher.com/4.0/pusher.min.js"></script><script>Pusher.logToConsole = true;var pusher = new Pusher("{{env("MIX_PUSHER_APP_KEY")}}", {cluster: '{{env('MIX_PUSHER_APP_CLUSTER')}}',encrypted: true});var channel = pusher.subscribe('my-channel'); //频道channel.bind('my-event', function(data) { //事件名console.log(data.info);});</script>
