多个聊天专用频道还是单个用户专用频道?

时间:2018-11-27 09:52:25

标签: laravel pusher

这两种解决方案中哪一种最明智?

  1. 每个聊天一个私人频道
  2. 每个用户一个私人频道

1。每次聊天

// app/channels.php
Broadcast::channel('chats.{chat}', function ($user, Chat $chat) {
    return $chat->users->contains($user);
});

// app/Events/MessageCreated.php
public function broadcastOn()
{
    return new PrivateChannel('chats.' . $this->message->chat->id);
}

// app/Observers/MessageObserver.php
public function created(Message $message)
{
    broadcast(new MessageCreated($message))->toOthers();
}
// Client-side
window.Echo.channel('chats.' + chatId).listen('MessageCreated', ev => {
    console.log(ev.message)
});

2。每个用户

// app/channels.php
Broadcast::channel('users.{user}', function ($currentUser, User $user) {
    return $currentUser->id === $user->id;
});

// app/Events/MessageCreated.php
public function broadcastOn()
{
    return new PrivateChannel('users.' . $this->user->id);
}

// app/Observers/MessageObserver.php
public function created(Message $message)
{
    $message->chat->users->each(function($user) use ($message) {
        broadcast(new MessageCreated($user, $message))->toOthers();
    });
}
// Client-side
window.Echo.channel('users.' + userId).listen('MessageCreated', ev => {
    console.log(ev.user, ev.message)
});

Laravel documentation似乎建议解决方案1 ​​...(以order为例)

0 个答案:

没有答案