0

所以我要使用 laravel 广播作为聊天应用程序,

我遵循Laravel 广播方法,

  • App\Providers\BroadcastServiceProviderproviders里面的数组中取消注释config/app.php

  • .env在 pusher 网站上注册,创建了一个频道,并用我的 pusher 频道信息填写了内部文件下面的字段

PUSHER_APP_ID
PUSHER_APP_KEY
PUSHER_APP_SECRET
PUSHER_APP_CLUSTER
  • 在我broadcast.php将默认设置为的配置文件中driverpusher我还添加了
'options' => [
    'cluster' => 'us2',
    'encrypted' => true,
],

根据我在推送面板中的频道信息在pusher数组内排列connections

  • composer require pusher/pusher-php-server "~3.0"使用命令在我的 laravel 项目上安装了 pusher php 包

这是我的活动课

<?php

namespace App\Events;
use App\User;
use App\TherapyMessage;
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;
use App\AppLog;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class TherapyMessageSent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * User that sent the message
     *
     * @var User
     */
    public $user;

    /**
     * Message details
     *
     * @var Message
     */
    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user, TherapyMessage $message)
    {
        $this->user = $user;
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        $message_id = $this->message->id;
        $user = $this->user;

        AppLog::create([
            'file_name' => __FILE__,
            'message' => "broadcast before send with Message ID of $message_id from $user->full_name"
        ]);

        return new PrivateChannel("therapy-chat.$message_id");
    }
}

  • AppLog是我用于在项目内部登录的模型
  • 我一开始尝试实现ShouldBroadcast接口,但也没有用
  • 我还在EventServiceProvider.php文件中注册了我的事件并运行php artisan event:generate命令,这是EventServiceProvider $listen数组:
protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
        TherapyMessageSent::class
    ],
];

我还在文件中的其他命名空间旁边导入了事件命名空间: use \App\Events\TherapyMessageSent;

这是我在routes/channels.php文件中定义的通道:


use App\AppLog;

Broadcast::channel('therapy-chat.{message_id}', function ($user, $message_id) {

    AppLog::create([
        'file_name' => __FILE__,
        'message' => "broadcast sending with Message ID of $message_id to $user->full_name"
    ]);

    if (!Auth::check()) return false;

    $message = \App\TherapyMessage::find($message_id);

    if (!$message) {

        AppLog::create([
            'file_name' => __FILE__,
            'message' => "Message with ID of $message_id Not Found for broadcasting"
        ]);

        return false;
    }

    $will_send = false;

    if ($therapist = $user->therapist) {
        $will_send = $therapist->id === $message->therapist_id;
    } else if ($patient = $user->patient) {
        $will_send = $message->patient_id === $patient->id;
    }

    if ($will_send) {

        AppLog::create([
            'file_name' => __FILE__,
            'message' => "Message with ID of $message_id broadcasted to $user->full_name"
        ]);
    }

    return $will_send;
});

最后,这是我的控制器方法:

public function sendToTherapist(Request $request) {

    $validation = \Validator::make($request->all(), ['message' => 'required']);

    if ($validation->fails()) return $this->validationError($validation);

    $user = \Auth::user();
    $patient = $user->patient;
    $therapist = $patient->therapist;

    if (!$therapist) return $this->errorWithMessage('Patient does not have Therapist');

    $message = \App\TherapyMessage::create([
        'patient_id' => $patient->id,
        'therapist_id' => $therapist->id,
        'type' => TherapyMessageType::TEXT,
        'text' => $request->message,
        'sender_role' => TherapyMessageSenderRole::PATIENT
    ]);

    broadcast(new TherapyMessageSent($user, $message))->toOthers();

    return $this->success(['id' => $message->id]);
}
  • 我的控制器类从 BaseController 扩展而来,BaseController 是一个自定义控制器类,具有辅助方法,例如success()validationError()errorWithMessage()

正如您在上面的代码中看到的那样,我填写$user$message使用了正确的值,并且请求可以正常工作

我认为通道方法甚至不会被触发,因为我AppLog在调用broadcast方法时检查表,只保存TherapyMessageSent事件broadcastOn函数内部的日志,甚至我在方法开头保存的日志channels.php也没有保存,所以我认为这个方法永远不会执行。

如果有人可以帮助我解决问题,我将不胜感激。

4

0 回答 0