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

Async Event Dispatcher Bundle Laravel Package

desarrolla2/async-event-dispatcher-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require desarrolla2/async-event-dispatcher-bundle in your Symfony project root. Ensure your composer.json includes the package under require.

  2. Bundle Registration Add the bundle to config/bundles.php (Symfony 4+) or app/AppKernel.php (Symfony 3):

    Desarrolla2\AsyncEventDispatcherBundle\AsyncEventDispatcherBundle::class => ['all' => true],
    
  3. Basic Configuration Define minimal config in config/packages/async_event_dispatcher.yaml:

    async_event_dispatcher:
        num_messages_per_execution: 1  # Default batch size
        maximum_num_of_consumers: 4    # Default worker count
    
  4. First Async Event Dispatch an event asynchronously in a controller/service:

    use Desarrolla2\AsyncEventDispatcherBundle\Event\Event;
    use Desarrolla2\AsyncEventDispatcherBundle\AsyncEventDispatcher;
    
    public function dispatchExample(AsyncEventDispatcher $dispatcher) {
        $event = new Event('my.event', ['data' => 'payload']);
        $dispatcher->dispatchAsync($event);
    }
    
  5. Verify Workers Run the consumer command in a separate terminal:

    php bin/console async:event:consume
    

Implementation Patterns

Core Workflow

  1. Dispatching Events

    • Use AsyncEventDispatcher to queue events:
      $dispatcher->dispatchAsync(new Event('user.created', ['userId' => 123]));
      
    • Events are stored in a queue (default: Doctrine DBAL) and processed asynchronously.
  2. Event Structure

    • Extend Event class or use plain arrays:
      $event = new Event('order.processed', ['orderId' => 456, 'status' => 'shipped']);
      
    • Include a unique event name (string) and payload (array/serializable data).
  3. Consumer Management

    • Start workers with:
      php bin/console async:event:consume --workers=8
      
    • Workers process events in batches (num_messages_per_execution).
  4. Integration with Symfony Events

    • Convert synchronous events to async:
      $dispatcher->dispatchAsync(new Event('kernel.request', ['request' => $request]));
      

Advanced Patterns

  • Priority Queues Extend the bundle’s queue table to add a priority column and filter events in the consumer:

    // In consumer service
    $events = $queue->getHighPriorityEvents();
    
  • Retry Logic Implement a retry_count field in the queue table and handle failures in the consumer:

    if ($event->getRetryCount() >= 3) {
        $this->logger->error('Max retries exceeded for event: ' . $event->getName());
    }
    
  • Delayed Events Add a scheduled_at column to the queue table and process events based on timestamps:

    $events = $queue->getEventsScheduledBefore(now());
    
  • Event Listeners as Async Wrap event listeners in async dispatchers:

    public function onUserRegistered(UserRegisteredEvent $event) {
        $asyncEvent = new Event('user.registered.async', ['user' => $event->getUser()]);
        $this->dispatcher->dispatchAsync($asyncEvent);
    }
    

Gotchas and Tips

Pitfalls

  1. Queue Table Schema

    • The bundle assumes a default table (async_event_queue). If using a custom schema, ensure:
      • id, event_name, payload, created_at, and processed_at columns exist.
      • payload must be serializable (use json_encode/json_decode for arrays).
  2. Worker Lifecycle

    • Workers do not auto-restart on crashes. Use a process manager (e.g., Supervisor) for production:
      [program:async-worker]
      command=php bin/console async:event:consume --workers=4
      autostart=true
      autorestart=true
      
  3. Payload Size Limits

    • Large payloads (>1MB) may cause DB timeouts. Compress data or use external storage (e.g., S3) for binaries.
  4. Event Ordering

    • Async dispatch does not guarantee order. Use a sequence_id field if order matters.
  5. Symfony Dependency Injection

    • The AsyncEventDispatcher service is not autowired by default. Register it explicitly in services.yaml:
      services:
          Desarrolla2\AsyncEventDispatcherBundle\AsyncEventDispatcher: ~
      

Debugging Tips

  • Check Queue Status Run php bin/console async:event:list to inspect pending events.

  • Log Worker Output Add logging to the consumer command:

    # config/services.yaml
    Desarrolla2\AsyncEventDispatcherBundle\Command\ConsumeCommand:
        arguments:
            $logger: '@logger'
    
  • Test Locally with In-Memory Queue Override the queue service in tests:

    $this->container->set('async_event_dispatcher.queue', new InMemoryQueue());
    

Extension Points

  1. Custom Queue Backend Replace the default DoctrineQueue with a custom implementation (e.g., RabbitMQ, Redis):

    async_event_dispatcher:
        queue:
            class: App\Queue\RedisQueue
    
  2. Event Serialization Override the serializer for complex objects:

    $event = new Event('complex.event', ['object' => $complexObject]);
    $event->setSerializer(function ($payload) {
        return serialize($payload);
    });
    
  3. Post-Processing Hooks Extend the consumer to add callbacks:

    // In consumer service
    $event->afterProcess(function ($event) {
        $this->analytics->track($event->getName());
    });
    
  4. Dynamic Worker Scaling Use environment variables for maximum_num_of_consumers:

    async_event_dispatcher:
        maximum_num_of_consumers: '%env(int:WORKER_COUNT, 4)%'
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony