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.
composer require centrifugal/phpcent:~6.0
$client = new \phpcent\Client(
env('CENTRIFUGO_API_URL', 'http://localhost:8000/api'),
env('CENTRIFUGO_API_KEY'),
env('CENTRIFUGO_SECRET_KEY')
);
$this->app->singleton(\phpcent\Client::class, function ($app) {
return new \phpcent\Client(
config('centrifugo.api_url'),
config('centrifugo.api_key'),
config('centrifugo.secret_key')
);
});
Publish a real-time message to a channel (e.g., for notifications):
use phpcent\Client;
class NotificationService {
protected $client;
public function __construct(Client $client) {
$this->client = $client;
}
public function sendNotification(string $channel, array $data) {
$this->client->publish($channel, $data);
}
}
Call it from a Laravel event listener or controller:
$notificationService->sendNotification('user.notifications', [
'message' => 'New comment added!',
'user_id' => auth()->id(),
]);
Securely generate a JWT token for client-side WebSocket connections:
$token = $this->client->generateConnectionToken(
auth()->id(), // Required user ID
time() + 3600 // Optional: Expiration timestamp (default: 24h)
);
Use in your frontend to authenticate WebSocket connections:
const connection = new Centrifuge(
'ws://your-centrifugo-server/api',
{ token: '<?= $token ?>' }
);
Leverage Laravel’s event system to trigger real-time updates:
// 1. Listen for events (e.g., new comment)
event(new CommentCreated($comment));
// 2. Dispatch a real-time event
class CommentCreated implements ShouldBroadcast {
use Dispatchable, InteractsWithSockets;
public function broadcastOn() {
return new Channel('comments.' . $this->comment->post_id);
}
public function toCentrifugo($notifiable) {
return [
'message' => 'New comment added',
'user_id' => $this->comment->user_id,
'content' => $this->comment->content,
];
}
}
// 3. Use phpcent to publish the event (optional: async via queues)
$client->publish('comments.' . $postId, $event->toCentrifugo($notifiable));
Track online users in a channel (e.g., for live chat):
// Get presence info for a channel
$presence = $client->presence('chat.room.123');
// Example response:
// {
// "chat.room.123": {
// "users": ["user1", "user2"],
// "count": 2
// }
// }
Reduce network overhead with batch API calls:
$batchData = [
['method' => 'publish', 'channel' => 'channel1', 'data' => ['msg' => 'Hello']],
['method' => 'subscribe', 'channel' => 'channel2', 'user_id' => 'user123'],
];
$client->batch($batchData);
Offload real-time publishing to a queue for scalability:
// Dispatch a job
PublishCentrifugoMessage::dispatch($channel, $data);
// Job implementation
class PublishCentrifugoMessage implements ShouldQueue {
use Dispatchable, InteractsWithQueue;
public function handle(Client $client) {
$client->publish($this->channel, $this->data);
}
}
Generate tokens dynamically during authentication:
// In your AuthController or middleware
public function login(Request $request) {
$user = Auth::login($request->user());
$token = app(\phpcent\Client::class)->generateConnectionToken(
$user->id,
now()->addHours(1)
);
return response()->json(['token' => $token]);
}
Adopt consistent channel naming for maintainability:
global.notificationsuser.{id}.activitypost.{id}.commentsteam.{id}.updatesExample:
$client->subscribe("user." . auth()->id() . ".notifications");
API Key/Secret Management:
.env and bind the client to the container with environment variables.config('centrifugo.secret_key') for dynamic updates.Token Expiration:
$token = $client->generateConnectionToken($userId, time() + 300); // 5 mins
Channel Subscription Leaks:
subscribe with unsubscribe:
$client->unsubscribe('user.' . $userId . '.notifications', $userId);
SSL/TLS Issues:
$client->setSafety(false); // Only for dev!
$client->setCert('/path/to/cert.pem');
$client->setCAPath('/path/to/ca.pem');
Batch API Limitations:
try {
$client->batch($batchData);
} catch (\phpcent\Exception $e) {
// Log and retry failed operations individually
}
Presence Data Staleness:
presenceStats for critical decisions (e.g., user availability).DNS Resolution Failures:
$client->forceIpResolveV4();
Enable Verbose Logging:
$client->setDebug(true); // Logs HTTP requests/responses
Check Laravel logs for phpcent debug output.
Validate API Responses: Always check response statuses:
$response = $client->publish('channel', ['data' => 'test']);
if ($response->getStatusCode() !== 200) {
throw new \Exception('Failed to publish: ' . $response->getBody());
}
Test Locally with Docker: Use the provided Docker setup to validate integrations:
docker run -d -p 8000:8000 --name centrifugo centrifugo/centrifugo centrifugo --api_insecure
Monitor Centrifugo Metrics:
Expose Centrifugo’s Prometheus metrics (/metrics endpoint) to track:
Custom JWT Claims: Extend token generation with metadata:
$token = $client->generateConnectionToken($userId, time() + 3600, [
'metadata' => ['role' => 'admin', 'scope' => 'global']
]);
Middleware for Requests: Add Laravel middleware to transform requests/responses:
$client->setMiddleware(function ($request, $next) {
$request->setHeader('X-Custom-Header', 'value');
return $next($request);
});
Event Listeners for API Calls:
Hook into phpcent events (e.g., before/after publish):
$client->on('publish', function ($channel, $data) {
How can I help you explore Laravel packages today?