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

Technical Evaluation

Architecture Fit

  • Real-time Pub/Sub Alignment: The package is a direct fit for Laravel applications requiring real-time features (e.g., notifications, live updates, collaborative tools) via Centrifugo’s HTTP API. The alignment with Centrifugo’s v5 HTTP API ensures compatibility with modern deployments, while maintaining backward compatibility for existing Laravel integrations.

    • Key Strengths:
      • Abstraction: Eliminates low-level WebSocket complexity, allowing TPMs to focus on business logic (e.g., event-driven workflows).
      • Protocol Stability: The v6.0.x release’s cleanup and API method extensions (e.g., batch, presenceStats) align with Centrifugo’s latest protocol, reducing edge-case failures.
      • Laravel Synergy: Works seamlessly with Laravel’s event system, queues, and authentication (e.g., JWT tokens via generateConnectionToken).
    • Limitations:
      • Centrifugo Lock-in: Tight coupling to Centrifugo’s architecture (e.g., channel-based pub/sub) may complicate future migrations to alternative real-time solutions (e.g., Pusher, Ably).
      • No Native Laravel Integration: Requires manual setup (e.g., service providers, middleware) for features like auth middleware or rate limiting.
  • Scalability Considerations:

    • Horizontal Scaling: Centrifugo’s architecture supports millions of concurrent connections, but Laravel’s PHP process model may become a bottleneck for high-throughput scenarios (e.g., 10K+ concurrent WebSocket connections). Mitigation: Use Laravel Horizon for queue-based pub/sub or offload to a dedicated microservice.
    • Resource Overhead: The package adds minimal overhead (~100KB), but Centrifugo’s server-side resources (CPU/memory) will dominate for large-scale deployments.

Integration Feasibility

  • Stack Compatibility:

    • PHP/Laravel: Fully compatible with PHP 8.1+ (per Centrifugo’s requirements) and Laravel’s dependency injection (e.g., bind phpcent\Client in AppServiceProvider).
    • Centrifugo Versions:
      • v5+: Native support (recommended for new projects).
      • v4: Requires phpcent v5.x (deprecated in favor of v6.x).
      • v3: Requires phpcent v4.x (unsupported in v6.x).
    • Async Support: Integrates with Laravel’s queues (e.g., publish() calls can be dispatched to centrifugo-publish queue).
  • Migration Path:

    • Greenfield Projects: Start with phpcent v6.0.3 + Centrifugo v5.x for latest features (e.g., batch API, improved token auth).
    • Legacy Systems:
      • Centrifugo v4: Downgrade to phpcent v5.x (no breaking changes).
      • Centrifugo v3: Use phpcent v4.x (drop PHP <7.0 support).
    • Zero-Downtime: The package’s API is stable; migrations can be tested in staging before rollout.
  • Compatibility Notes:

    • SSL/TLS: Supports self-signed certs (setCert(), setCAPath()) and IPv6/IPv4 resolution (forceIpResolveV4()).
    • Timeouts: Configurable via setConnectTimeoutOption() and setTimeoutOption() (critical for unreliable networks).
    • JSON Handling: Supports associative arrays (setUseAssoc(true)) for Laravel-friendly responses.

Key Questions for TPM

  1. Centrifugo Deployment:

    • Is Centrifugo already deployed in production, or is this a new integration? If new, evaluate hosting (self-managed vs. managed services like Centrifugo Cloud).
    • What’s the expected scale (concurrent connections, messages/sec)? This dictates whether Laravel’s PHP processes or a dedicated microservice should handle phpcent operations.
  2. Authentication Flow:

    • How will JWT tokens (e.g., generateConnectionToken) integrate with Laravel’s auth system (e.g., Sanctum, Passport)? Will tokens be stored in the database or issued per-request?
    • Are private channels required? If so, ensure Centrifugo’s channel auth is configured.
  3. Failure Modes:

    • How will Centrifugo downtime be handled? (e.g., fallback to polling, circuit breakers).
    • What’s the retry strategy for failed HTTP API calls (e.g., publish())? The package lacks built-in retries; Laravel’s queue retries or a custom decorator may be needed.
  4. Observability:

    • Are metrics (e.g., message latency, connection counts) needed? Centrifugo provides Prometheus metrics, but phpcent doesn’t expose them natively.
    • How will logging be centralized? The package logs to stderr by default; Laravel’s Monolog integration may be required.
  5. Testing:

    • Is a local Centrifugo instance available for integration tests? The package’s test suite assumes Dockerized Centrifugo (docker run -p 8000:8000 centrifugo/centrifugo).
    • Are load tests planned? Simulate high concurrency (e.g., 1K+ connections) to validate Laravel + Centrifugo stability.
  6. Alternatives:

    • Why not use Laravel Echo (Pusher-compatible) or native WebSocket libraries (e.g., ratchet/ratchet)? Evaluate tradeoffs:
      • Centrifugo: Best for self-hosted, scalable pub/sub with minimal ops overhead.
      • Pusher: Easier setup but vendor lock-in and cost at scale.
      • Ratchet: More control but higher maintenance.

Integration Approach

Stack Fit

  • Laravel Integration Points:

    1. Service Provider:
      // app/Providers/CentrifugoServiceProvider.php
      public function register()
      {
          $this->app->singleton(\phpcent\Client::class, function ($app) {
              return new \phpcent\Client(
                  config('centrifugo.api_url'),
                  config('centrifugo.api_key'),
                  config('centrifugo.secret_key')
              )->setUseAssoc(true);
          });
      }
      
    2. Config File:
      // config/centrifugo.php
      return [
          'api_url' => env('CENTRIFUGO_API_URL', 'http://localhost:8000/api'),
          'api_key' => env('CENTRIFUGO_API_KEY'),
          'secret_key' => env('CENTRIFUGO_SECRET_KEY'),
          'timeout' => 2.0,
      ];
      
    3. Event Listeners:
      // app/Listeners/PublishCentrifugoEvent.php
      public function handle(Published $event)
      {
          $client = app(\phpcent\Client::class);
          $client->publish('notifications', $event->data);
      }
      
    4. Middleware (Optional): Attach to routes requiring real-time updates (e.g., WebSocket auth):
      public function handle($request, Closure $next)
      {
          $token = app(\phpcent\Client::class)
              ->setSecret(config('centrifugo.secret_key'))
              ->generateConnectionToken(auth()->id());
          $request->headers->set('Centrifugo-Token', $token);
          return $next($request);
      }
      
  • Async Workflow:

    • Dispatch publish() calls to a queue (e.g., centrifugo-publish) to decouple Laravel from Centrifugo’s network latency:
      // In a Laravel job
      public function handle()
      {
          $client = app(\phpcent\Client::class);
          $client->publish('channel', ['data' => $this->data]);
      }
      
  • Testing Strategy:

    • Unit Tests: Mock phpcent\Client (e.g., using Mockery).
    • Integration Tests: Spin up a Dockerized Centrifugo instance (as per the package’s test setup) and verify:
      • Token generation (generateConnectionToken).
      • Pub/sub operations (publish/subscribe).
      • Error cases (e.g., invalid API keys, timeouts).

Migration Path

Phase Action Items Dependencies
Assessment 1. Audit existing real-time features (e.g., polling, Server-Sent Events). Dev team, product roadmap.
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
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