Laravel进阶系列笔记--(二十三)Laravel 广播-使用私有频道广播-4

作者: 温新

分类: 【Laravel】

阅读: 1931

时间: 2021-09-01 13:11:18

作者:温新

时间:2021-07-31

hi,我是温新,一名PHPer

本系列采用Laravel8.x演示。

第一步:创建事件

php artisan make:event DiscussionEvent

第二步:编写事件

//Events/DiscussionEvent.php
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class DiscussionEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    // 实例对象
    public $discussion = null;

    public function __construct($discussion)
    {
        $this->discussion = $discussion;
    }
    
    public function broadcastOn()
    {
        // 私有广播。这个主题ID必须携带
        return new PrivateChannel('study.'.$this->discussion->topic->id);
    }
}

第三步:权限验证

// routes/channels.php
// 所有登录用户都可以讨论
Broadcast::channel('study.{topic}', function ($user, \App\Models\Topic $topic) {
    return true;
});

第四步:广播配置

1)安装Pusher PHP SDK包

composer require pusher/pusher-php-server "~4.0"

2)Laravel Echo服务安装

npm install --save laravel-echo pusher-js
npm install
npm run watch

3)将驱动修改为pusher

// .env
BROADCAST_DRIVER=pusher

4)配置相关key

// .env
PUSHER_APP_ID=你的ID
PUSHER_APP_KEY=你的KEY
PUSHER_APP_SECRET=你的SECRET
PUSHER_APP_CLUSTER=ap3

5)打开广播服务

// config/app.php

// 打开这个注释,使之生效
App\Providers\BroadcastServiceProvider::class,

6)配置广播服务连接

// config/boradcasting.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'),
        'useTLS' => true,
        'curl_options' => [
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
        ],
    ],
],

7)修改URL

// .env
// 将值修改为自己的域名
APP_URL=http://cast.com

第五步:广播事件

// Api/DiscussionController.php
public function store(Request $request, $topicId)
{
    // 数据入库并返回给当前路由
    $disscusson = Discussion::create([
        'body'   =>  $request->body,
        'user_id'   =>  $request->user()->id,
        'topic_id'  =>  $topicId
    ]);
	 // 自己不广播,只广播给别人
    broadcast(new DiscussionEvent($disscusson))->toOthers();
    return $disscusson->load('user');
}

第六步:前端客户端监听事件

// resources/js/bootstrap.js

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'ef8d661555b6fdf9b528',
    cluster: 'ap3',
    forceTLS: true
});

vue组件监听

// resources/js/components/TopicComponent.vue
// 初始化对事件进行监听
mounted() {
    window.Echo.private('study.'+this.topic.id)
    .listen('DiscussionEvent', (discussion) => {
    	this.discussions.push(discussion);
    });

    // 对应主题讨论的数据
    this.discussions = this.topic.discussions;
},

到这里就可以进行测试了。打开谷歌和火狐浏览器,分别登录李四和王五这两个用户,然后对话题进行讨论,不用刷新页面就可以看到了。

第七步:控制用户权限

修改channels.php

// channels.php
Broadcast::channel('study.{topic}', function ($user, \App\Models\Topic $topic) {
    return $topic->users->contains($user);
});

到这里,私有广播完成。

我是温新

每天进步一点点,就一点点

请登录后再评论