larahook / simple-centrifugo
centrifugo的连接和订阅令牌
v0.0.7
2024-04-02 09:44 UTC
Requires
- php: ^8.0
- firebase/php-jwt: *
- laravel/framework: ^10.0|^11.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.52
README
安装
composer require larahook/simple-centrifugo
驱动
使用simple-centrifugo
驱动添加centrifugo
连接到config/broadcasting.php
'connections' => [ 'centrifugo' => [ 'driver' => 'simple-centrifugo', 'token_hmac_secret_key' => env('CENTRIFUGO_TOKEN_HMAC_SECRET_KEY', ''), 'api_key' => env('CENTRIFUGO_API_KEY', ''), 'url' => env('CENTRIFUGO_URL', 'https://:8000'), // centrifugo api url 'verify' => env('CENTRIFUGO_VERIFY', false), // Verify host ssl if centrifugo uses this 'ssl_key' => env('CENTRIFUGO_SSL_KEY', null), // Self-Signed SSl Key for Host (require verify=true) ], ]
用法
获取客户端令牌
- 将
SimpleCentrifugo
特质添加到您的类中 - 使用
getConnectionToken
方法获取连接令牌 - 并使用
getSubscriptionToken
方法获取订阅令牌
use Carbon\Carbon; use Larahook\SimpleCentrifugo\Trait\SimpleCentrifugo; class ChannelService { use SimpleCentrifugo; /** * @param int $userId * @param Carbon $exp * * @return array */ public function getConnToken(int $userId, Carbon $exp): array { return $this->getConnectionToken($userId, $exp); } /** * @param int $userId * @param array $channels * @param Carbon $exp * * @return array */ public function getSubsToken(int $userId, array $channels, Carbon $exp): array { return $this->getSubscriptionToken($userId, $channels, $exp); } }
事件示例
通过laravel事件将消息推送到centrifugo通道
namespace App\Events; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Auth; class PersonalEvent implements ShouldBroadcastNow { use Dispatchable; use SerializesModels; /** * @param array $message */ public function __construct(public array $message) {} /** * Get the channels the event should broadcast on. * * @return array */ public function broadcastOn() { return ['personal:#'.Auth::id()]; } public function broadcastAs() { return 'PersonalEvent'; } }
事件执行
PersonalEvent::dispatch(['info']);