Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpcent Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:
    composer require centrifugal/phpcent:~6.0
    
  2. Initialize the client in your Laravel service provider or a dedicated config file:
    $client = new \phpcent\Client(
        env('CENTRIFUGO_API_URL', 'http://localhost:8000/api'),
        env('CENTRIFUGO_API_KEY'),
        env('CENTRIFUGO_SECRET_KEY')
    );
    
  3. Bind to Laravel’s service container (optional but recommended for dependency injection):
    $this->app->singleton(\phpcent\Client::class, function ($app) {
        return new \phpcent\Client(
            config('centrifugo.api_url'),
            config('centrifugo.api_key'),
            config('centrifugo.secret_key')
        );
    });
    

First Use Case: Publishing a Message

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(),
]);

First Use Case: Generating a Connection Token

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 ?>' }
);

Implementation Patterns

Workflow: Laravel Event-Driven Pub/Sub

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));

Workflow: Presence Tracking

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
//     }
// }

Workflow: Batch Operations

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);

Integration with Laravel Queues

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);
    }
}

Integration with Laravel Auth

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]);
}

Pattern: Channel Naming Conventions

Adopt consistent channel naming for maintainability:

  • Public channels: global.notifications
  • User-specific: user.{id}.activity
  • Resource-specific: post.{id}.comments
  • Private groups: team.{id}.updates

Example:

$client->subscribe("user." . auth()->id() . ".notifications");

Gotchas and Tips

Pitfalls

  1. API Key/Secret Management:

    • Pitfall: Hardcoding credentials in client initialization.
    • Fix: Use Laravel’s .env and bind the client to the container with environment variables.
    • Tip: Rotate secrets regularly and use Laravel’s config('centrifugo.secret_key') for dynamic updates.
  2. Token Expiration:

    • Pitfall: Using default token expiration (24h) for short-lived sessions (e.g., OAuth flows).
    • Fix: Pass a custom expiration timestamp:
      $token = $client->generateConnectionToken($userId, time() + 300); // 5 mins
      
  3. Channel Subscription Leaks:

    • Pitfall: Subscribing users to channels without unsubscribing, leading to memory leaks.
    • Fix: Always pair subscribe with unsubscribe:
      $client->unsubscribe('user.' . $userId . '.notifications', $userId);
      
  4. SSL/TLS Issues:

    • Pitfall: Invalid SSL certificates causing connection failures.
    • Fix: Disable safety checks for testing (not production):
      $client->setSafety(false); // Only for dev!
      
    • Production Tip: Use proper certificates or configure CA paths:
      $client->setCert('/path/to/cert.pem');
      $client->setCAPath('/path/to/ca.pem');
      
  5. Batch API Limitations:

    • Pitfall: Assuming batch operations are atomic or transactional.
    • Fix: Handle partial failures gracefully:
      try {
          $client->batch($batchData);
      } catch (\phpcent\Exception $e) {
          // Log and retry failed operations individually
      }
      
  6. Presence Data Staleness:

    • Pitfall: Relying on presenceStats for critical decisions (e.g., user availability).
    • Fix: Combine with client-side heartbeats or application-level tracking.
  7. DNS Resolution Failures:

    • Pitfall: IPv6 resolution timeouts in Docker or cloud environments.
    • Fix: Force IPv4 resolution:
      $client->forceIpResolveV4();
      

Debugging Tips

  1. Enable Verbose Logging:

    $client->setDebug(true); // Logs HTTP requests/responses
    

    Check Laravel logs for phpcent debug output.

  2. 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());
    }
    
  3. 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
    
  4. Monitor Centrifugo Metrics: Expose Centrifugo’s Prometheus metrics (/metrics endpoint) to track:

    • Connection counts
    • Message throughput
    • Latency spikes

Extension Points

  1. Custom JWT Claims: Extend token generation with metadata:

    $token = $client->generateConnectionToken($userId, time() + 3600, [
        'metadata' => ['role' => 'admin', 'scope' => 'global']
    ]);
    
  2. Middleware for Requests: Add Laravel middleware to transform requests/responses:

    $client->setMiddleware(function ($request, $next) {
        $request->setHeader('X-Custom-Header', 'value');
        return $next($request);
    });
    
  3. Event Listeners for API Calls: Hook into phpcent events (e.g., before/after publish):

    $client->on('publish', function ($channel, $data) {
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle