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

Centrifugo Laravel Package

baks-dev/centrifugo

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require baks-dev/centrifugo
    

    Verify PHP 8.4+ compatibility in your project.

  2. Configure .env Add Centrifugo connection details:

    CENTRIFUGO_URL=ws://centrifugo:8000/connection/websocket
    CENTRIFUGO_SECRET=your_secure_jwt_secret
    CENTRIFUGO_REDIS_URL=redis://redis:6379
    
  3. Install Assets Run the bundle installer:

    php bin/console baks:assets:install
    
  4. First Use Case: Publish an Event Dispatch a Centrifugo event from a Laravel controller or command:

    use BaksDev\Centrifugo\Event\CentrifugoEvent;
    
    event(new CentrifugoEvent('chat:room1', ['message' => 'Hello, world!']));
    
  5. Frontend Integration Include the Centrifugo JS client in your frontend:

    <script src="https://unpkg.com/centrifugo@latest/client.js"></script>
    

    Connect to the WebSocket endpoint:

    const client = new CentrifugoClient();
    client.connect('ws://your-laravel-app/centrifugo/connection/websocket', {
      token: 'user_jwt_token'
    });
    client.subscribe('chat:room1', (data) => {
      console.log('Received:', data);
    });
    

Implementation Patterns

Core Workflows

  1. Event-Driven Pub/Sub

    • Publish: Use Laravel events to broadcast to Centrifugo channels:
      // In a controller or service
      event(new CentrifugoEvent('notifications:user1', [
          'type' => 'alert',
          'message' => 'New message received'
      ]));
      
    • Subscribe: Frontend subscribes to channels via the Centrifugo JS client (as shown above).
  2. Private Channels

    • Use channel patterns with user-specific prefixes:
      event(new CentrifugoEvent('private-user:{$userId}', ['data' => ...]));
      
    • Frontend subscribes dynamically:
      client.subscribe(`private-user:${userId}`, (data) => { ... });
      
  3. Presence Tracking

    • Leverage Centrifugo’s built-in presence API:
      // In a Centrifugo config (if extended)
      'presence': {
          'enabled': true,
          'max': 10000
      }
      
    • Query presence from frontend:
      client.presence('chat:room1').get((err, presence) => {
          console.log('Users online:', presence);
      });
      
  4. Authentication

    • Generate JWT tokens in Laravel and pass them to Centrifugo:
      use BaksDev\Centrifugo\Facades\Centrifugo;
      
      $token = Centrifugo::generateToken($userId, ['role' => 'admin']);
      
    • Use the token in frontend connections:
      client.connect('ws://...', { token: 'generated_jwt_token' });
      

Integration Tips

  • Laravel Events to Centrifugo Channels Create a mapping layer in a service:

    class CentrifugoPublisher
    {
        public function publishToChannel(string $channel, array $data)
        {
            event(new CentrifugoEvent($channel, $data));
        }
    }
    
  • Queue Events for Scalability Dispatch Centrifugo events asynchronously:

    event(new CentrifugoEvent(...))->dispatchSync(false);
    
  • Channel Management Dynamically create channels based on business logic:

    $channel = "user:{$userId}:activity";
    event(new CentrifugoEvent($channel, ['action' => 'login']));
    
  • Error Handling Catch and log Centrifugo exceptions:

    try {
        event(new CentrifugoEvent(...));
    } catch (\BaksDev\Centrifugo\Exception\CentrifugoException $e) {
        Log::error('Centrifugo error: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Dependency Conflicts

    • baks-dev/centrifugo depends on baks-dev/core, which may introduce Symfony components not aligned with Laravel’s default stack. Run:
      composer why baks-dev/core
      
      to audit dependencies.
  2. Centrifugo Version Lock

    • The package is locked to Centrifugo 5.4. Upgrading to Centrifugo 6.x may require manual intervention or a package update.
  3. Redis Configuration

    • Ensure your Laravel Redis driver matches Centrifugo’s Redis backend. Misconfigurations can cause connection issues.
  4. Token Management

    • Centrifugo uses JWT for authentication. If using Laravel’s built-in auth (e.g., Sanctum), you’ll need to bridge tokens manually:
      use BaksDev\Centrifugo\Facades\Centrifugo;
      
      $token = Centrifugo::generateToken(
          auth()->id(),
          ['roles' => auth()->user()->roles]
      );
      
  5. Frontend Connection Issues

    • Common causes:
      • Incorrect WebSocket URL (must match CENTRIFUGO_URL in .env).
      • Missing or expired JWT tokens.
      • CORS restrictions (ensure Centrifugo’s allow_origin is configured).
  6. Channel Naming Collisions

    • Avoid dynamic channel names that could conflict with Centrifugo’s reserved patterns (e.g., private-*, presence-*).

Debugging

  1. Centrifugo Logs

    • Check Centrifugo’s logs (default: /var/log/centrifugo.log) for connection/auth issues:
      journalctl -u centrifugo -f  # If running as a service
      
  2. Laravel Logging

    • Enable debug logging for the package:
      'logging' => [
          'channel' => 'single',
          'level' => 'debug',
      ],
      
      in config/centrifugo.php (if it exists).
  3. Network Inspection

    • Use browser dev tools (Network tab) or wscat to test WebSocket connections:
      wscat -c ws://your-centrifugo-url/connection/websocket
      
  4. Redis Monitoring

    • Monitor Redis pub/sub backlog:
      redis-cli MONITOR
      
      or use redis-cli --scan --pattern "*".

Configuration Quirks

  1. Asset Installation

    • The baks:assets:install command may fail if file permissions are restrictive. Run:
      chmod -R 755 storage/bootstrap/cache
      
  2. Environment Variables

    • Ensure CENTRIFUGO_SECRET is unique and securely stored (not hardcoded).
  3. Centrifugo Config Overrides

    • Custom Centrifugo settings (e.g., config.json) may require extending the package’s config. Check for extension points in the package’s Resources/config directory.

Extension Points

  1. Custom Event Handlers

    • Extend the CentrifugoEvent class to add metadata:
      class CustomCentrifugoEvent extends CentrifugoEvent
      {
          public function __construct(string $channel, array $data, array $metadata = [])
          {
              parent::__construct($channel, array_merge($data, $metadata));
          }
      }
      
  2. Middleware for Auth

    • Add custom token validation by extending Centrifugo’s auth logic:
      // In a service provider
      Centrifugo::extend(function ($app) {
          $app->bind(\BaksDev\Centrifugo\Contracts\Authenticator::class, function () {
              return new CustomAuthenticator();
          });
      });
      
  3. Channel Filters

    • Implement channel access control:
      use BaksDev\Centrifugo\Contracts\ChannelFilter;
      
      class UserChannelFilter implements ChannelFilter
      {
          public function allow(string $channel, string $userId): bool
          {
              return str_starts_with($channel, "private-user:{$userId}");
          }
      }
      
  4. Metrics and Monitoring

    • Integrate with Laravel Horizon or Prometheus by extending Centrifugo’s metrics endpoint:
      // Example: Add a custom metric
      Centrifugo::metrics(function () {
          return [
              'laravel_channels' => Centrifugo::getChannelCount(),
          ];
      });
      

Performance Tips

  1. Batch Events

    • Reduce WebSocket overhead by batching events:
      $batch = collect([...]);
      event(new CentrifugoEvent('batch:channel', $batch->toArray()));
      
  2. Connection Pooling

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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