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

Ekko Broadcast Bundle Laravel Package

edwin-luijten/ekko-broadcast-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require edwin-luijten/ekko-broadcast-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        EdwinLuijten\EkkoBroadcastBundle\EkkoBroadcastBundle::class => ['all' => true],
    ];
    
  2. Configuration: Update config/packages/ekko_broadcast.yaml (or create it) with your Ekko server URL:

    ekko_broadcast:
        server_url: 'ws://your-ekko-server:8080'
        secret_key: '%env(EKKO_SECRET_KEY)%'
    
  3. First Use Case: Trigger a broadcast event in a controller:

    use EdwinLuijten\EkkoBroadcastBundle\Event\BroadcastEvent;
    
    public function updateData(Request $request)
    {
        // ... update data logic ...
    
        $event = new BroadcastEvent('data-updated', ['new_data' => $data]);
        $this->get('ekko_broadcast')->broadcast($event);
    }
    
  4. Client-Side Setup: Include Ekko client library in your frontend (e.g., JavaScript):

    const ekko = new Ekko('ws://your-ekko-server:8080', 'client-secret');
    ekko.on('data-updated', (data) => {
        console.log('Received:', data);
    });
    

Implementation Patterns

Core Workflows

  1. Event Broadcasting:

    • Symfony Events: Integrate with Symfony’s event system for consistency:
      $dispatcher->dispatch(new BroadcastEvent('event-name', $payload));
      
    • Custom Events: Extend BroadcastEvent for domain-specific logic:
      class UserUpdatedEvent extends BroadcastEvent {
          public function __construct($userId, array $changes) {
              parent::__construct('user-updated', compact('userId', 'changes'));
          }
      }
      
  2. Channel-Based Broadcasting: Use channels to target specific clients (e.g., users.123 for user ID 123):

    $event = new BroadcastEvent('chat-message', ['message' => 'Hello'], ['channel' => 'users.123']);
    
  3. Middleware Integration: Attach middleware to filter or transform broadcasts:

    # config/packages/ekko_broadcast.yaml
    ekko_broadcast:
        middleware:
            - EdwinLuijten\EkkoBroadcastBundle\Middleware\AuthMiddleware
            - App\Middleware\LogBroadcastMiddleware
    
  4. Private vs. Public Events:

    • Private: Encrypted payloads for sensitive data.
    • Public: Unencrypted for non-sensitive updates.

Integration Tips

  1. Laravel Bridge: Use a Symfony-to-Laravel adapter (e.g., spatie/laravel-symfony-bridge) if migrating from Laravel:

    // In a Laravel service provider:
    $this->app->bind('ekko_broadcast', function ($app) {
        return new \EdwinLuijten\EkkoBroadcastBundle\EkkoBroadcastService(
            $app['config']['ekko_broadcast.server_url'],
            $app['config']['ekko_broadcast.secret_key']
        );
    });
    
  2. ReactPHP Integration: For async processing, integrate with ReactPHP’s event loop:

    use React\EventLoop\Factory;
    
    $loop = Factory::create();
    $ekko = new \EdwinLuijten\EkkoBroadcastBundle\EkkoClient($serverUrl, $secret);
    $loop->run();
    
  3. Testing: Mock the broadcast service in PHPUnit:

    $mockBroadcast = $this->createMock(EkkoBroadcastInterface::class);
    $mockBroadcast->expects($this->once())->method('broadcast');
    $this->container->set('ekko_broadcast', $mockBroadcast);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • Last updated in 2016; verify compatibility with modern Symfony (4.4+/5.x).
    • Check for forks (e.g., this one) if issues arise.
  2. Secret Key Management:

    • Hardcoding secrets in config/ is unsafe. Use environment variables:
      secret_key: '%env(EKKO_SECRET)%'
      
    • Rotate keys periodically and update clients accordingly.
  3. Connection Limits:

    • Ekko may throttle connections. Monitor server logs for ECONNREFUSED or EHOSTUNREACH.
  4. Payload Size:

    • Large payloads (>1MB) may cause timeouts. Compress data client-side:
      ekko.send('event', pako.deflate(JSON.stringify(data)));
      

Debugging

  1. Enable Verbose Logging:

    ekko_broadcast:
        debug: true
    

    Logs appear in var/log/dev.log.

  2. Wireshark/tcpdump: Inspect raw WebSocket traffic for malformed packets:

    tcpdump -i any port 8080 -w ekko_traffic.pcap
    
  3. Ekko Server Logs: Check /var/log/ekko/ekko.log for server-side errors (e.g., auth failures).


Extension Points

  1. Custom Transports: Extend EkkoTransport to support alternative protocols (e.g., MQTT):

    class MqttTransport extends EkkoTransport {
        public function send($event) {
            // MQTT-specific logic
        }
    }
    
  2. Event Serialization: Override serialization in BroadcastEvent for custom formats (e.g., Protocol Buffers):

    class ProtobufEvent extends BroadcastEvent {
        public function serialize() {
            return \Google\Protobuf\Internal\Encoder::encode($this->payload);
        }
    }
    
  3. Rate Limiting: Implement a decorator to throttle broadcasts:

    class RateLimitedBroadcast implements EkkoBroadcastInterface {
        private $decorated;
        private $limit;
    
        public function __construct(EkkoBroadcastInterface $decorated, int $limit) {
            $this->decorated = $decorated;
            $this->limit = $limit;
        }
    
        public function broadcast(BroadcastEvent $event) {
            if ($this->isAllowed()) {
                $this->decorated->broadcast($event);
            }
        }
    }
    

Laravel-Specific Quirks

  1. Service Provider Binding: Bind the bundle’s service to Laravel’s container in AppServiceProvider:

    public function register() {
        $this->app->singleton('ekko_broadcast', function ($app) {
            return new \EdwinLuijten\EkkoBroadcastBundle\EkkoBroadcastService(
                config('ekko_broadcast.server_url'),
                config('ekko_broadcast.secret_key')
            );
        });
    }
    
  2. Queue Integration: Offload broadcasts to a queue (e.g., Redis) to avoid blocking requests:

    use Illuminate\Support\Facades\Queue;
    
    Queue::push(function () {
        $this->app->make('ekko_broadcast')->broadcast($event);
    });
    
  3. Route Caching: Clear route cache after adding Ekko-related routes:

    php artisan route:clear
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware