centrifugal/phpcent
PHP client for Centrifugo v5 HTTP API. Publish/broadcast messages, manage subscriptions, presence, history, channels and info, run batch calls, and configure timeouts. Also generates JWT connection and channel subscription tokens using your Centrifugo secret.
Installation:
composer require centrifugal/phpcent:~6.0
Basic Client Initialization:
$client = new \phpcent\Client("http://your-centrifugo-server:8000/api", "<API_KEY>", "<SECRET_KEY>");
First Use Case: Publishing a Message
$client->publish("chat:general", ["message" => "Hello, world!"]);
Client class (for advanced options like timeouts, SSL, or batch operations).phpcent can replace Pusher’s HTTP API calls directly.$token = $client->generateConnectionToken($userId, $expiresAt);
// Pass `$token` to frontend for WebSocket connection.
$token = $client->generateSubscriptionToken($userId, "private:chat", $expiresAt);
$token = $client->generateConnectionToken($userId, $expiresAt, ["role" => "admin"]);
// Single channel
$client->publish("notifications", ["type" => "alert"]);
// Multiple channels (broadcast)
$client->broadcast(["chat:room1", "chat:room2"], ["message" => "Announcement"]);
$presence = $client->presence("chat:general");
// Returns array of connected users and their metadata.
$client->batch([
["method" => "publish", "params" => ["channel" => "logs", "data" => ["event" => "started"]]],
["method" => "subscribe", "params" => ["channel" => "logs", "user" => "user123"]],
]);
// config/services.php
'centrifugo' => [
'api_url' => env('CENTRIFUGO_API_URL'),
'api_key' => env('CENTRIFUGO_API_KEY'),
'secret' => env('CENTRIFUGO_SECRET'),
];
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(\phpcent\Client::class, function ($app) {
return new \phpcent\Client(
config('services.centrifugo.api_url'),
config('services.centrifugo.api_key'),
config('services.centrifugo.secret')
);
});
}
// app/Listeners/PublishNotification.php
public function handle(NotificationSent $event)
{
app(\phpcent\Client::class)->publish("notifications", $event->data);
}
// Track cursor positions in a shared doc
$client->publish("doc:123:cursors", ["user" => "alice", "position" => 42]);
$onlineUsers = $client->presence("chat:lobby");
// Update UI to show "3 users online".
$token = $client->generateConnectionToken($userId, time() + 300); // 5 mins
// In your frontend, handle token expiration by:
// 1. Detecting `401 Unauthorized` from Centrifugo.
// 2. Calling a Laravel endpoint to generate a new token.
// 3. Reconnecting with the new token.
try {
$client->publish("critical", $data);
} catch (\phpcent\Exception\ClientException $e) {
if ($e->getCode() === 429) { // Rate limited
sleep(1);
retry();
}
}
$client->setLogger(new \Monolog\Logger('centrifugo'));
$mock = Mockery::mock(\phpcent\Client::class);
$mock->shouldReceive('publish')->once()->with("test", ["data"]);
docker run -d -p 8000:8000 --name centrifugo_test centrifugo/centrifugo centrifugo --api_insecure
API Key vs. Secret Key:
publish, subscribe).generateConnectionToken, generateSubscriptionToken).InvalidArgumentException.Token Claims:
generateConnectionToken now mandates a $userId (even if empty string for anonymous users).sub claim (user ID) for private channels.SSL/TLS Issues:
setCert() and setCAPath() to avoid cURL errors.
$client->setCert("/path/to/cert.pem")->setCAPath("/path/to/ca.pem");
forceIpResolveV4() if your system struggles with IPv6.Batch API Quirks:
publish and subscribe if order dependency exists.Presence Data:
Timeouts:
setTimeoutOption(0) disables timeouts (not recommended for production).setConnectTimeoutOption() affects connection establishment; setTimeoutOption() affects request processing.Enable Logging:
$client->setLogger(new \Monolog\Logger('centrifugo', [
new \Monolog\Handler\StreamHandler(storage_path('logs/centrifugo.log'), Monolog\Logger::DEBUG),
]));
Raw Responses:
$response = $client->info();
\Log::debug("Centrifugo API Response:", [$response->getBody()]);
Common Errors:
setUseAssoc(true) for associative arrays).--api flag).Custom HTTP Client:
\phpcent\Client to use Guzzle or Symfony’s HttpClient:
$client = new \phpcent\Client($url, $apiKey, $secret);
$client->setHttpClient(new \GuzzleHttp\Client());
Token Generators:
$client->setTokenGenerator(function ($userId, $expiresAt, $meta = []) {
return \Firebase\JWT\JWT::encode([
'sub' => $userId,
'exp' => $expiresAt,
'custom_claim' => 'value',
], $client->get
How can I help you explore Laravel packages today?