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

Faye App Bundle Laravel Package

cravler/faye-app-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Run composer require cravler/faye-app-bundle:4.x-dev in your Laravel project (note: this is a Symfony bundle, but can be adapted for Laravel via Symfony Bridge).
  2. Enable Bundle: Manually register in config/app.php under providers:
    Cravler\FayeAppBundle\CravlerFayeAppBundle::class,
    
    (Laravel 8+ uses config/bundles.php if using Symfony components directly.)
  3. Routing: Add to routes/web.php:
    require __DIR__.'/../vendor/cravler/faye-app-bundle/src/Resources/config/routing.php';
    
  4. JavaScript: Include in your Blade layout:
    @stack('scripts')
    @fayeAppScripts
    
    (Use @stack for dynamic script loading.)

First Use Case: Basic Pub/Sub

Create a custom entry point to handle real-time events:

// app/EntryPoints/MyEventEntryPoint.php
namespace App\EntryPoints;

use Cravler\FayeAppBundle\EntryPoint\AbstractEntryPoint;

class MyEventEntryPoint extends AbstractEntryPoint
{
    public function onSubscribe($clientId, $channel) {
        $this->publish($channel, "Welcome to {$channel}!");
    }
}

Register it in config/services.php:

'entry_points' => [
    'my_events' => App\EntryPoints\MyEventEntryPoint::class,
],

Implementation Patterns

Core Workflows

  1. Event-Driven Architecture:

    • Extend AbstractEntryPoint to handle subscriptions (onSubscribe), messages (onMessage), and disconnections (onUnsubscribe).
    • Use $this->publish($channel, $data) to broadcast to clients.
  2. Channel Management:

    • Dynamically create channels via createChannel($name, $options) in your entry point’s constructor.
    • Example: Private channels for authenticated users:
      $this->createChannel("user:{$userId}", ['auth' => true]);
      
  3. Authentication:

    • Override isAuthorized($clientId, $channel) to validate access:
      public function isAuthorized($clientId, $channel) {
          return auth()->id() === $this->extractUserIdFromChannel($channel);
      }
      
  4. Integration with Laravel:

    • Service Providers: Bind entry points in AppServiceProvider:
      public function register() {
          $this->app->bind('my.entry.point', function() {
              return new MyEventEntryPoint();
          });
      }
      
    • Event Listeners: Trigger Laravel events from Faye callbacks:
      public function onMessage($clientId, $channel, $data) {
          event(new FayeMessageReceived($data));
      }
      
  5. Frontend Integration:

    • Use fayeAppScripts in Blade to auto-load Faye client:
      // Auto-generated by the bundle
      const faye = new FayeClient('/faye');
      faye.subscribe('/channel', (message) => {
          console.log(message);
      });
      

Gotchas and Tips

Common Pitfalls

  1. CORS Issues:

    • Ensure your Faye server (/faye endpoint) has CORS headers. Add middleware:
      // app/Http/Middleware/Cors.php
      public function handle($request, Closure $next) {
          if ($request->is('/faye*')) {
              return response()->json([], 200, [
                  'Access-Control-Allow-Origin' => '*',
                  'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
              ]);
          }
          return $next($request);
      }
      
  2. Channel Naming Collisions:

    • Prefix channels with namespaces (e.g., app:notifications) to avoid conflicts with other services.
  3. Memory Leaks:

    • Unsubscribed clients may linger. Explicitly call $this->unsubscribe($clientId) in onUnsubscribe.
  4. Laravel-Specific Quirks:

    • Service Container: The bundle assumes Symfony’s DI. For Laravel, manually resolve dependencies:
      $this->container->get('auth')->user();
      
    • Configuration: Override default Faye settings in config/faye.php (if created):
      'mount' => '/laravel-faye',
      'timeout' => 30,
      

Debugging Tips

  1. Log Faye Events: Add a logger to your entry point:

    use Psr\Log\LoggerInterface;
    
    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }
    
    public function onMessage($clientId, $channel, $data) {
        $this->logger->debug("Message on {$channel}: " . json_encode($data));
    }
    
  2. Test with faye-client: Use the Faye WebSocket client to manually test channels:

    const client = new Faye.Client('http://localhost/faye');
    client.subscribe('/test', (msg) => console.log(msg));
    
  3. Check Faye Server Logs: Enable debug mode in your entry point:

    public function __construct() {
        $this->setDebug(true); // Logs all Faye events
    }
    

Extension Points

  1. Custom Transports: Override getTransport() to use alternative WebSocket servers (e.g., Ratchet):

    protected function getTransport() {
        return new RatchetTransport('ws://localhost:8080');
    }
    
  2. Middleware Pipeline: Add preprocessing to messages:

    public function onMessage($clientId, $channel, $data) {
        $processed = $this->processData($data);
        $this->publish($channel, $processed);
    }
    
  3. Laravel Horizon Integration: Offload Faye processing to queues:

    public function onMessage($clientId, $channel, $data) {
        dispatch(new ProcessFayeMessage($data))->onQueue('faye');
    }
    
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.
besmartand-pro/php-quality-config
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