centrifugal/phpcent
PHP client for Centrifugo v5 HTTP API. Publish and broadcast to channels, manage subscriptions, presence and history, and run batch calls. Also generates JWT connection and subscription tokens. Composer-ready with configurable timeouts.
Install the package via Composer:
composer require centrifugal/phpcent:~6.0
Initialize the client in your Laravel service provider or a dedicated class:
use phpcent\Client;
$client = new Client(
env('CENTRIFUGO_API_URL', 'http://localhost:8000/api'),
env('CENTRIFUGO_API_KEY'),
env('CENTRIFUGO_SECRET_KEY')
);
Store credentials in .env:
CENTRIFUGO_API_URL=http://localhost:8000/api
CENTRIFUGO_API_KEY=your_api_key_here
CENTRIFUGO_SECRET_KEY=your_secret_key_here
First use case: Publish a message
$client->publish('chat:general', ['message' => 'Hello, world!']);
phpcent/Client (for advanced configurations like timeouts or SSL).AppServiceProvider:
$this->app->singleton(Client::class, function ($app) {
return new Client(
$app['config']['centrifugo.api_url'],
$app['config']['centrifugo.api_key'],
$app['config']['centrifugo.secret_key']
);
});
$client->publish('notifications:user:1', ['type' => 'alert', 'data' => $payload]);
$client->broadcast(['chat:room:1', 'chat:room:2'], ['message' => 'Announcement']);
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class PublishCentrifugoMessage implements ShouldQueue
{
use Dispatchable, Queueable;
public function handle(Client $client)
{
$client->publish('channel', $this->data);
}
}
$token = $client->generateConnectionToken($userId, time() + 3600); // 1-hour TTL
$token = $client->generateSubscriptionToken($userId, 'private:chat', time() + 1800); // 30-min TTL
$token = $client->generateConnectionToken(
$userId,
time() + 3600,
['role' => 'admin']
);
$client->subscribe('chat:room:1', $userId);
$client->unsubscribe('chat:room:1', $userId);
$client->disconnect($userId);
$presence = $client->presence('chat:room:1');
$history = $client->history('notifications:user:1');
$client->historyRemove('notifications:user:1'); // Clear history
$client->batch([
['method' => 'publish', 'channel' => 'channel1', 'data' => $data1],
['method' => 'subscribe', 'channel' => 'channel2', 'user' => $userId],
]);
// config/centrifugo.php
return [
'api_url' => env('CENTRIFUGO_API_URL'),
'api_key' => env('CENTRIFUGO_API_KEY'),
'secret_key' => env('CENTRIFUGO_SECRET_KEY'),
'timeout' => 5.0,
];
// AppServiceProvider.php
$this->app->bind(Client::class, function ($app) {
$client = new Client(
$app['config']['centrifugo.api_url'],
$app['config']['centrifugo.api_key'],
$app['config']['centrifugo.secret_key']
);
$client->setTimeoutOption($app['config']['centrifugo.timeout']);
return $client;
});
// Listen to model events and publish updates
User::created(function ($user) {
$client = app(Client::class);
$client->publish("user:{$user->id}:created", $user->toArray());
});
// Convert Centrifugo responses to Laravel API Resources
public function getChannelPresence(Client $client, $channel)
{
$presence = $client->presence($channel);
return new ChannelPresenceResource($presence);
}
// tests/Feature/CentrifugoTest.php
public function test_publish_message()
{
$client = Mockery::mock(Client::class);
$client->shouldReceive('publish')
->once()
->with('test:channel', ['data' => 'test']);
$this->app->instance(Client::class, $client);
// Test your logic here...
}
API Key vs. Secret Key:
publish, presence).generateConnectionToken, generateSubscriptionToken).401 Unauthorized errors.Token Expiration:
generateConnectionToken or generateSubscriptionToken expire unless a TTL is specified.time() + 3600) for security.Channel Naming:
:) for hierarchy (e.g., private:chat:room1).SSL/TLS Issues:
$client->setSafety(false); // Disables SSL verification (insecure!)
or provide a CA bundle:
$client->setCAPath('/path/to/ca.pem');
setCert() for client certificate authentication if required.Timeouts:
$client->setConnectTimeoutOption(10); // 10 seconds
$client->setTimeoutOption(30); // 30 seconds
Batch Requests:
Presence Data:
presenceStats for aggregated data (e.g., online user counts).History Limits:
historyRemove to clear old messages or adjust Centrifugo’s config.Enable Verbose Logging:
$client->setDebug(true); // Logs raw HTTP requests/responses
Check Laravel logs for phpcent debug output.
Check Centrifugo Logs:
stdout (or a file if configured).--verbose for detailed logs.Validate JSON Responses:
setUseAssoc(true) to decode responses as associative arrays:
$client->setUseAssoc(true);
$response = $client->info(); // Returns array, not stdClass
How can I help you explore Laravel packages today?