Weave 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

Web Socket Bundle Laravel Package

drosalys-web/web-socket-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require drosalys-web/web-socket-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Drosalys\WebSocketBundle\DrosalysWebSocketBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console drosalys:websocket:install
    

    Edit config/packages/drosalys_websocket.yaml to define your WebSocket server settings (e.g., host, port, SSL).

  3. First Use Case: Basic Client Connection Use the provided JavaScript client to connect to your WebSocket endpoint:

    const socket = new WebSocket('ws://your-symfony-app.com/ws');
    socket.onopen = () => console.log('Connected!');
    socket.onmessage = (event) => console.log('Message:', event.data);
    
  4. Symfony Integration Enable the WebSocket route in your routes.yaml:

    drosalys_websocket:
        path: /ws
        methods: [GET]
    

Implementation Patterns

Workflow: Real-Time Features

  1. Event-Driven Architecture

    • Use Symfony’s event system to trigger WebSocket broadcasts:
      use Drosalys\WebSocketBundle\Event\WebSocketEvent;
      
      $event = new WebSocketEvent('chat_message', ['text' => 'Hello!']);
      $this->get('event_dispatcher')->dispatch(WebSocketEvent::NAME, $event);
      
  2. Authentication & Authorization

    • Secure WebSocket routes with Symfony’s security component:
      # config/packages/security.yaml
      firewalls:
          websocket:
              pattern: ^/ws
              stateless: true
              anonymous: false
              provider: app_user_provider
      
  3. Broadcasting to Specific Clients

    • Use topics or client IDs to target specific connections:
      $this->get('drosalys_websocket.client_manager')->broadcast(
          'user_123',
          'private_message',
          ['content' => 'Hi there!']
      );
      
  4. Handling Messages

    • Create a custom message handler:
      use Drosalys\WebSocketBundle\Message\WebSocketMessage;
      
      class ChatMessageHandler implements WebSocketMessageHandlerInterface
      {
          public function handle(WebSocketMessage $message) {
              // Process $message->getData() and broadcast responses
          }
      }
      
    • Register the handler in services.yaml:
      services:
          App\Handler\ChatMessageHandler:
              tags: ['drosalys_websocket.message_handler']
      
  5. Integration with Symfony Controllers

    • Use dependency injection to access the WebSocket service:
      use Drosalys\WebSocketBundle\Service\WebSocketService;
      
      class ChatController extends AbstractController
      {
          public function __construct(private WebSocketService $wsService) {}
      
          public function sendNotification() {
              $this->wsService->broadcast('all', 'notification', ['text' => 'New update!']);
          }
      }
      

Gotchas and Tips

Pitfalls

  1. CORS Issues

    • Ensure your WebSocket server and frontend are configured to handle CORS:
      # config/packages/drosalys_websocket.yaml
      cors:
          allow_origin: ['http://your-frontend.com']
      
    • Test with tools like WebSocket King to debug.
  2. Connection Limits

    • The bundle defaults to a limited number of concurrent connections. Adjust in config:
      max_connections: 1000
      
  3. Message Serialization

    • By default, messages are serialized as JSON. Customize with a serializer:
      serializer:
          class: App\Serializer\CustomWebSocketSerializer
      
  4. Symfony Cache Conflicts

    • If using Symfony’s cache, clear it after config changes:
      php bin/console cache:clear
      
  5. Debugging WebSocket Events

    • Enable debug mode in config/packages/drosalys_websocket.yaml:
      debug: true
      
    • Check logs at var/log/dev.log for WebSocket-related errors.

Tips

  1. Use Topics for Scalability

    • Organize broadcasts by topics (e.g., chat, notifications) to avoid flooding all clients.
  2. Leverage Symfony’s Dependency Injection

    • Inject WebSocketService or ClientManager into services/controllers for reusable logic.
  3. Custom Middleware

    • Extend functionality with middleware:
      use Drosalys\WebSocketBundle\Middleware\WebSocketMiddlewareInterface;
      
      class AuthMiddleware implements WebSocketMiddlewareInterface
      {
          public function handle(WebSocketRequest $request, callable $next) {
              if (!$request->isAuthenticated()) {
                  throw new \RuntimeException('Unauthorized');
              }
              return $next($request);
          }
      }
      
    • Register in services.yaml:
      tags: ['drosalys_websocket.middleware']
      
  4. Load Testing

    • Use tools like k6 or Autobahn to simulate high traffic.
  5. SSL/TLS Configuration

    • For production, enable SSL in config:
      ssl:
          enabled: true
          cert_file: '%kernel.project_dir%/config/ssl/cert.pem'
          key_file: '%kernel.project_dir%/config/ssl/key.pem'
      
  6. Fallback for Older Browsers

    • Provide a polyfill for WebSocket support in legacy browsers:
      if (!window.WebSocket) {
          window.WebSocket = require('websocket-polyfill');
      }
      
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator