这两种解决方案中哪一种最明智?
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
为例)