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 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
    
  3. First use case: Publish a message

    $client->publish('chat:general', ['message' => 'Hello, world!']);
    

Where to Look First

  • API Reference: Centrifugo HTTP API Docs (for method signatures and payload structures).
  • Package Source: phpcent/Client (for advanced configurations like timeouts or SSL).
  • Laravel Integration: Bind the client to Laravel’s service container in 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']
        );
    });
    

Implementation Patterns

Core Workflows

1. Publishing Messages

  • Single Channel:
    $client->publish('notifications:user:1', ['type' => 'alert', 'data' => $payload]);
    
  • Broadcast to Multiple Channels:
    $client->broadcast(['chat:room:1', 'chat:room:2'], ['message' => 'Announcement']);
    
  • Async Publishing (Laravel Jobs):
    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);
        }
    }
    

2. Token Generation

  • Connection Token (for client auth):
    $token = $client->generateConnectionToken($userId, time() + 3600); // 1-hour TTL
    
  • Subscription Token (for channel access):
    $token = $client->generateSubscriptionToken($userId, 'private:chat', time() + 1800); // 30-min TTL
    
  • With Metadata (e.g., user roles):
    $token = $client->generateConnectionToken(
        $userId,
        time() + 3600,
        ['role' => 'admin']
    );
    

3. Channel Management

  • Subscribe/Unsubscribe Users:
    $client->subscribe('chat:room:1', $userId);
    $client->unsubscribe('chat:room:1', $userId);
    
  • Disconnect User:
    $client->disconnect($userId);
    

4. State Inspection

  • Presence Data:
    $presence = $client->presence('chat:room:1');
    
  • Channel History:
    $history = $client->history('notifications:user:1');
    $client->historyRemove('notifications:user:1'); // Clear history
    

5. Batch Operations

$client->batch([
    ['method' => 'publish', 'channel' => 'channel1', 'data' => $data1],
    ['method' => 'subscribe', 'channel' => 'channel2', 'user' => $userId],
]);

Laravel-Specific Patterns

Service Container Binding

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

Event-Driven Integration

// Listen to model events and publish updates
User::created(function ($user) {
    $client = app(Client::class);
    $client->publish("user:{$user->id}:created", $user->toArray());
});

API Resource Responses

// Convert Centrifugo responses to Laravel API Resources
public function getChannelPresence(Client $client, $channel)
{
    $presence = $client->presence($channel);
    return new ChannelPresenceResource($presence);
}

Testing with Mocks

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

Gotchas and Tips

Pitfalls

  1. API Key vs. Secret Key:

    • API Key: Required for all HTTP API calls (e.g., publish, presence).
    • Secret Key: Only needed for token generation (generateConnectionToken, generateSubscriptionToken).
    • Gotcha: Forgetting to set the API key will result in 401 Unauthorized errors.
  2. Token Expiration:

    • Tokens generated with generateConnectionToken or generateSubscriptionToken expire unless a TTL is specified.
    • Tip: Always include a TTL (e.g., time() + 3600) for security.
  3. Channel Naming:

    • Centrifugo channels are case-sensitive and use colons (:) for hierarchy (e.g., private:chat:room1).
    • Gotcha: Typos in channel names will silently fail (no error, just no delivery).
  4. SSL/TLS Issues:

    • If Centrifugo uses a self-signed certificate, set:
      $client->setSafety(false); // Disables SSL verification (insecure!)
      
      or provide a CA bundle:
      $client->setCAPath('/path/to/ca.pem');
      
    • Tip: Use setCert() for client certificate authentication if required.
  5. Timeouts:

    • Default timeouts may be too short for high-latency environments.
    • Tip: Adjust with:
      $client->setConnectTimeoutOption(10); // 10 seconds
      $client->setTimeoutOption(30);        // 30 seconds
      
  6. Batch Requests:

    • Batch requests are atomic—if one fails, the entire batch fails.
    • Tip: Use for low-frequency operations (e.g., bulk unsubscribes).
  7. Presence Data:

    • Presence data is not persisted across server restarts.
    • Tip: Use presenceStats for aggregated data (e.g., online user counts).
  8. History Limits:

    • Channel history is limited (default: 100 messages).
    • Tip: Call historyRemove to clear old messages or adjust Centrifugo’s config.

Debugging Tips

  1. Enable Verbose Logging:

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

    Check Laravel logs for phpcent debug output.

  2. Check Centrifugo Logs:

    • Centrifugo logs HTTP API calls to stdout (or a file if configured).
    • Tip: Run Centrifugo with --verbose for detailed logs.
  3. Validate JSON Responses:

    • Use setUseAssoc(true) to decode responses as associative arrays:
      $client->setUseAssoc(true);
      $response = $client->info(); // Returns array, not stdClass
      
  4. Handle Exceptions:

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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky