2026-03-01 00:48:51 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 文件功能:好友添加广播事件
|
|
|
|
|
*
|
|
|
|
|
* 当用户 A 添加用户 B 为好友时,向 B 的私有频道广播此事件,
|
|
|
|
|
* B 的客户端收到后展示弹窗通知。
|
2026-03-01 00:54:10 +08:00
|
|
|
* 携带 has_added_back 字段:若 B 已将 A 加为好友则为 true(双向好友),
|
|
|
|
|
* 否则为 false,前端提示 B 可以点击回加。
|
2026-03-01 00:48:51 +08:00
|
|
|
*
|
|
|
|
|
* @author ChatRoom Laravel
|
|
|
|
|
*
|
|
|
|
|
* @version 1.0.0
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
namespace App\Events;
|
|
|
|
|
|
|
|
|
|
use Illuminate\Broadcasting\Channel;
|
|
|
|
|
use Illuminate\Broadcasting\InteractsWithSockets;
|
|
|
|
|
use Illuminate\Broadcasting\PrivateChannel;
|
|
|
|
|
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
|
|
|
|
|
use Illuminate\Foundation\Events\Dispatchable;
|
|
|
|
|
use Illuminate\Queue\SerializesModels;
|
|
|
|
|
|
|
|
|
|
class FriendAdded implements ShouldBroadcast
|
|
|
|
|
{
|
|
|
|
|
use Dispatchable, InteractsWithSockets, SerializesModels;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 构造好友添加事件。
|
|
|
|
|
*
|
2026-03-01 00:54:10 +08:00
|
|
|
* @param string $fromUsername 发起添加的用户名(A)
|
|
|
|
|
* @param string $toUsername 被添加的用户名(B,接收通知方)
|
|
|
|
|
* @param bool $hasAddedBack B 是否已将 A 加为好友(互相添加=true)
|
2026-03-01 00:48:51 +08:00
|
|
|
*/
|
|
|
|
|
public function __construct(
|
|
|
|
|
public readonly string $fromUsername,
|
|
|
|
|
public readonly string $toUsername,
|
2026-03-01 00:54:10 +08:00
|
|
|
public readonly bool $hasAddedBack = false,
|
2026-03-01 00:48:51 +08:00
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 广播到被添加用户的私有频道,仅本人可见。
|
|
|
|
|
*/
|
|
|
|
|
public function broadcastOn(): Channel
|
|
|
|
|
{
|
|
|
|
|
return new PrivateChannel('user.'.$this->toUsername);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2026-03-01 00:54:10 +08:00
|
|
|
* 广播负载:包含发起人信息和互相好友状态,供前端弹窗使用。
|
2026-03-01 00:48:51 +08:00
|
|
|
*
|
2026-03-01 00:54:10 +08:00
|
|
|
* @return array<string, mixed>
|
2026-03-01 00:48:51 +08:00
|
|
|
*/
|
|
|
|
|
public function broadcastWith(): array
|
|
|
|
|
{
|
|
|
|
|
return [
|
|
|
|
|
'from_username' => $this->fromUsername,
|
|
|
|
|
'to_username' => $this->toUsername,
|
|
|
|
|
'type' => 'friend_added',
|
2026-03-01 00:54:10 +08:00
|
|
|
'has_added_back' => $this->hasAddedBack,
|
2026-03-01 00:48:51 +08:00
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
}
|