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 Dispatcher Bundle Laravel Package

bodaclick/async-dispatcher-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require bodaclick/async-dispatcher-bundle
    

    Register the bundle in config/bundles.php:

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

    php bin/console config:dump-reference Bodaclick\AsyncDispatcherBundle\Configuration
    

    Configure the queue connection in config/packages/async_dispatcher.yaml:

    async_dispatcher:
        queue_connection: 'sync' # or 'database', 'redis', etc.
        queue_name: 'async_events'
    
  3. First Use Case Dispatch an event asynchronously in a controller or service:

    use Symfony\Component\EventDispatcher\EventDispatcherInterface;
    use Bodaclick\AsyncDispatcherBundle\AsyncDispatcher;
    
    class MyController extends AbstractController
    {
        public function __construct(
            private AsyncDispatcher $asyncDispatcher
        ) {}
    
        public function handleEvent()
        {
            $event = new MyEvent();
            $this->asyncDispatcher->dispatch($event); // Async dispatch
        }
    }
    

Implementation Patterns

Core Workflow

  1. Event Dispatching Replace synchronous EventDispatcherInterface with AsyncDispatcher for non-critical events:

    $this->asyncDispatcher->dispatch(new UserRegisteredEvent($user));
    
  2. Queue Integration Configure the bundle to use a queue driver (e.g., database, redis):

    async_dispatcher:
        queue_connection: 'redis'
        queue_name: 'async_events'
    

    Ensure the queue worker is running:

    php bin/console messenger:consume async_events -vv
    
  3. Event Listeners Register listeners as usual in services.yaml or via annotations:

    services:
        App\EventListener\MyEventListener:
            tags:
                - { name: 'kernel.event_listener', event: 'app.my_event', method: 'onMyEvent' }
    
  4. Batching Events For high-volume events, batch them to reduce queue overhead:

    $this->asyncDispatcher->dispatchBatch([$event1, $event2, $event3]);
    

Integration Tips

  • Symfony Messenger: Leverage Symfony’s Messenger component for advanced queue handling (e.g., retries, middleware).
  • Event Prioritization: Use queue priorities if your queue driver supports it (e.g., Redis Sorted Sets).
  • Testing: Mock AsyncDispatcher in tests to avoid real queue interactions:
    $this->asyncDispatcher = $this->createMock(AsyncDispatcher::class);
    $this->asyncDispatcher->method('dispatch')->willReturn(true);
    

Gotchas and Tips

Pitfalls

  1. Queue Worker Requirement

    • Issue: Events won’t fire if the queue worker isn’t running.
    • Fix: Start the worker in production:
      php bin/console messenger:consume async_events --time-limit=300
      
    • Tip: Use Supervisor or systemd to keep the worker alive.
  2. Synchronous Fallback

    • Issue: The bundle defaults to synchronous dispatch if the queue fails.
    • Fix: Configure a fallback strategy in config/packages/async_dispatcher.yaml:
      async_dispatcher:
          fallback_on_failure: false # Set to true to throw exceptions
      
  3. Event Serialization

    • Issue: Complex events (e.g., with closures, resources) may fail to serialize.
    • Fix: Ensure events implement Serializable or use __serialize()/__unserialize():
      class MyEvent implements Serializable {
          public function serialize() { /* ... */ }
          public function unserialize($data) { /* ... */ }
      }
      
  4. Database Queue Limitations

    • Issue: Database queues (e.g., doctrine) may struggle with high event volumes.
    • Tip: Use Redis or another high-performance queue for production.

Debugging

  • Queue Inspection: Check pending events with:
    php bin/console messenger:failed:list
    php bin/console messenger:consume async_events --time-limit=1
    
  • Logging: Enable debug mode to log dispatched events:
    async_dispatcher:
         debug: true
    

Extension Points

  1. Custom Queue Handlers Extend the bundle’s AsyncDispatcher to support custom queue logic:

    class CustomAsyncDispatcher extends AsyncDispatcher {
        protected function getQueueConnection(): ConnectionInterface {
            return new CustomQueueConnection();
        }
    }
    
  2. Event Filtering Filter events before dispatching by overriding the dispatch() method:

    $this->asyncDispatcher->setFilter(function ($event) {
        return $event instanceof AllowedEvent;
    });
    
  3. Middleware Add middleware to the queue (Symfony Messenger style):

    framework:
        messenger:
            transports:
                async_events:
                    dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                    options:
                        middleware: [validate_event, log_event]
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager