-
首先注册一个Pusher账号,登陆后台创建app获取相关key
-
laravel中配置Pusher
- 导入Pusher SDK
composer require pusher/pusher-php-server
-
- 配置Pusher证书,config/broadcasting.php 注意修改默认项!
<?php return [ 'default' => env('BROADCAST_DRIVER', 'pusher'), 'connections' => [ '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, ], ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'log' => [ 'driver' => 'log', ], 'null' => [ 'driver' => 'null', ], ], ];
-
- 建立事件并配置,Events/TestEvent.php 如果该事件没有继承 Illuminate\Contracts\Broadcasting\ShouldBroadcast接口,那么触发使事件将不会发送事件至 pusher 服务器上
php artisan make:event TestEvent
<?php namespace 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 implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; public $content; /** * Create a new event instance. * @return void */ public function __construct($content) {$this->content = $content; }
/** * Get the channels the event should broadcast on. * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { // return new PrivateChannel('channel-name'); // return ['my-channel']; return new Channel('my-channel'); } /** * 指定广播事件(对应前端的事件) * @return string */ public function broadcastAs() { return 'my-event'; } /** * 获取广播数据,默认是广播的public属性的数据 */ public function broadcastWith() { return [ 'content' => $this->content ]; } }
-
-
触发事件
-
event(new \App\Events\TestEvent('test'));
-
前端代码实现可以在Pusher后台文档中直接copy使用即可