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

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require centrifugal/phpcent:~6.0
    
  2. Basic Client Initialization:

    $client = new \phpcent\Client("http://your-centrifugo-server:8000/api", "<API_KEY>", "<SECRET_KEY>");
    
    • Replace placeholders with your Centrifugo server URL, API key, and secret key (found in Centrifugo config).
  3. First Use Case: Publishing a Message

    $client->publish("chat:general", ["message" => "Hello, world!"]);
    
    • Verify the message appears in your Centrifugo admin dashboard or client-side subscription.

Where to Look First

  • API Reference: Centrifugo HTTP API Docs (for method signatures and payload structures).
  • Package Source: Client class (for advanced options like timeouts, SSL, or batch operations).
  • Laravel Integration: Check if your app uses Laravel Echo or Pusher-compatible clientsphpcent can replace Pusher’s HTTP API calls directly.

Implementation Patterns

Core Workflows

1. Token-Based Authentication

  • Connection Tokens (for client-side auth):
    $token = $client->generateConnectionToken($userId, $expiresAt);
    // Pass `$token` to frontend for WebSocket connection.
    
  • Subscription Tokens (for private channels):
    $token = $client->generateSubscriptionToken($userId, "private:chat", $expiresAt);
    
  • Meta Data Support (v5.1.0+):
    $token = $client->generateConnectionToken($userId, $expiresAt, ["role" => "admin"]);
    

2. Channel Management

  • Publish/Broadcast:
    // Single channel
    $client->publish("notifications", ["type" => "alert"]);
    
    // Multiple channels (broadcast)
    $client->broadcast(["chat:room1", "chat:room2"], ["message" => "Announcement"]);
    
  • Presence Tracking:
    $presence = $client->presence("chat:general");
    // Returns array of connected users and their metadata.
    

3. Batch Operations

  • Efficient API Calls:
    $client->batch([
        ["method" => "publish", "params" => ["channel" => "logs", "data" => ["event" => "started"]]],
        ["method" => "subscribe", "params" => ["channel" => "logs", "user" => "user123"]],
    ]);
    

4. Laravel Integration

  • Service Provider Binding:
    // 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')
            );
        });
    }
    
  • Event Listeners:
    // app/Listeners/PublishNotification.php
    public function handle(NotificationSent $event)
    {
        app(\phpcent\Client::class)->publish("notifications", $event->data);
    }
    

5. Real-Time Features

  • Live Collaboration:
    // Track cursor positions in a shared doc
    $client->publish("doc:123:cursors", ["user" => "alice", "position" => 42]);
    
  • Presence-Driven UI:
    $onlineUsers = $client->presence("chat:lobby");
    // Update UI to show "3 users online".
    

Advanced Patterns

Token Expiration Handling

  • Short-Lived Tokens:
    $token = $client->generateConnectionToken($userId, time() + 300); // 5 mins
    
  • Refresh Logic:
    // 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.
    

Error Handling

  • Retry Logic:
    try {
        $client->publish("critical", $data);
    } catch (\phpcent\Exception\ClientException $e) {
        if ($e->getCode() === 429) { // Rate limited
            sleep(1);
            retry();
        }
    }
    
  • Logging:
    $client->setLogger(new \Monolog\Logger('centrifugo'));
    

Testing

  • Mocking the Client:
    $mock = Mockery::mock(\phpcent\Client::class);
    $mock->shouldReceive('publish')->once()->with("test", ["data"]);
    
  • Dockerized Centrifugo:
    docker run -d -p 8000:8000 --name centrifugo_test centrifugo/centrifugo centrifugo --api_insecure
    

Gotchas and Tips

Pitfalls

  1. API Key vs. Secret Key:

    • API Key: Used for HTTP API authentication (e.g., publish, subscribe).
    • Secret Key: Required only for generating tokens (generateConnectionToken, generateSubscriptionToken).
    • Gotcha: Forgetting to set the secret key when generating tokens will throw InvalidArgumentException.
  2. Token Claims:

    • User ID Required: generateConnectionToken now mandates a $userId (even if empty string for anonymous users).
    • Subscription Tokens: Must include the sub claim (user ID) for private channels.
  3. SSL/TLS Issues:

    • Self-Signed Certs: Use setCert() and setCAPath() to avoid cURL errors.
      $client->setCert("/path/to/cert.pem")->setCAPath("/path/to/ca.pem");
      
    • IPv6 Resolution: Force IPv4 with forceIpResolveV4() if your system struggles with IPv6.
  4. Batch API Quirks:

    • Order Matters: Methods in a batch are executed sequentially. Avoid mixing publish and subscribe if order dependency exists.
    • Error Handling: Batch failures return the first error; use individual calls for granular control.
  5. Presence Data:

    • Metadata Limits: Presence data is stored in-memory by Centrifugo. Large datasets may cause performance issues.
  6. Timeouts:

    • Default Values: setTimeoutOption(0) disables timeouts (not recommended for production).
    • Connect vs. Request: setConnectTimeoutOption() affects connection establishment; setTimeoutOption() affects request processing.

Debugging Tips

  1. Enable Logging:

    $client->setLogger(new \Monolog\Logger('centrifugo', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/centrifugo.log'), Monolog\Logger::DEBUG),
    ]));
    
  2. Raw Responses:

    $response = $client->info();
    \Log::debug("Centrifugo API Response:", [$response->getBody()]);
    
  3. Common Errors:

    • 401 Unauthorized: Check API key or secret.
    • 400 Bad Request: Validate JSON payloads (use setUseAssoc(true) for associative arrays).
    • 500 Server Error: Ensure Centrifugo is running and the HTTP API is enabled (--api flag).

Extension Points

  1. Custom HTTP Client:

    • Extend \phpcent\Client to use Guzzle or Symfony’s HttpClient:
      $client = new \phpcent\Client($url, $apiKey, $secret);
      $client->setHttpClient(new \GuzzleHttp\Client());
      
  2. Token Generators:

    • Override token generation for custom claims:
      $client->setTokenGenerator(function ($userId, $expiresAt, $meta = []) {
          return \Firebase\JWT\JWT::encode([
              'sub' => $userId,
              'exp' => $expiresAt,
              'custom_claim' => 'value',
          ], $client->get
      
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon