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

bbit/async-dispatcher-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bbit/async-dispatcher-bundle:2.5.0
    

    Add to config/bundles.php:

    return [
        // ...
        BBIT\AsyncDispatcherBundle\BBITAsyncDispatcherBundle::class => ['all' => true],
    ];
    
  2. Enable Async Dispatcher: Configure in config/packages/bbit_async_dispatcher.yaml:

    bbit_async_dispatcher:
        enabled: true
    
  3. First Use Case: Dispatch an event asynchronously in a controller:

    use BBIT\AsyncDispatcherBundle\AsyncDispatcherInterface;
    use Symfony\Component\HttpKernel\KernelEvents;
    
    public function someAction(AsyncDispatcherInterface $asyncDispatcher)
    {
        $asyncDispatcher->dispatch(new MyEvent(), KernelEvents::TERMINATE);
    }
    

Where to Look First

  • Bundle Docs: Check BBITAsyncDispatcherBundle for configuration options.
  • Event Dispatching: Review AsyncDispatcherInterface for available methods.
  • Kernel Events: Use Symfony\Component\HttpKernel\KernelEvents constants for event timing.

Implementation Patterns

Core Workflow

  1. Dispatch Events Asynchronously:

    $asyncDispatcher->dispatch($event, $eventName, $priority = 0);
    
    • Events are stored in memory until KernelEvents::TERMINATE.
  2. Event Priorities: Use priorities to control dispatch order (higher priority = earlier dispatch):

    $asyncDispatcher->dispatch($event, KernelEvents::TERMINATE, 100);
    
  3. Integration with Symfony Events:

    • Replace synchronous dispatcher->dispatch() with $asyncDispatcher->dispatch() for non-critical events.
    • Useful for:
      • Logging
      • Analytics
      • Background tasks (e.g., sending emails, notifications)

Common Use Cases

  • Non-Blocking Analytics:
    $asyncDispatcher->dispatch(new TrackUserEvent($user), 'user.track');
    
  • Deferred Notifications:
    $asyncDispatcher->dispatch(new SendWelcomeEmailEvent($user), 'user.welcome_email');
    
  • Batch Processing: Dispatch multiple events in a loop without blocking the request:
    foreach ($users as $user) {
        $asyncDispatcher->dispatch(new ProcessUserEvent($user), 'user.process');
    }
    

Integration Tips

  • Dependency Injection: Inject AsyncDispatcherInterface into services where async dispatch is needed.
  • Event Subscribers: Extend existing subscribers to support async dispatch:
    public static function getSubscribedEvents()
    {
        return [
            'user.created' => ['onUserCreated', 0],
            'user.created.async' => ['onUserCreatedAsync', 0], // Async variant
        ];
    }
    
  • Testing: Mock AsyncDispatcherInterface in tests to verify events are dispatched:
    $mockDispatcher = $this->createMock(AsyncDispatcherInterface::class);
    $this->container->set('async_dispatcher', $mockDispatcher);
    

Gotchas and Tips

Pitfalls

  1. Memory Leaks:

    • Events are stored in memory until terminate. For long-running requests (e.g., CLI commands), clear the dispatcher manually:
      $asyncDispatcher->clear();
      
    • Avoid dispatching large payloads (e.g., entire datasets) asynchronously.
  2. Event Ordering:

    • Async events are dispatched in priority order but not guaranteed to respect original dispatch order.
    • Use unique priorities or event names to avoid conflicts.
  3. Terminate Dependency:

    • The bundle relies on KernelEvents::TERMINATE. If your app exits early (e.g., via exit() or exceptions), events may not dispatch.
    • For CLI commands, ensure terminate is called or dispatch events synchronously.
  4. Thread Safety:

    • The dispatcher is not thread-safe. Avoid using it in multi-threaded environments (e.g., Symfony Messenger workers).

Debugging

  • Check Dispatcher State:
    $events = $asyncDispatcher->getQueuedEvents();
    // Debug $events to inspect pending dispatches.
    
  • Log Undispatched Events: Override the dispatcher to log failed dispatches:
    $asyncDispatcher->setListener(function ($event) {
        // Custom logic (e.g., log to Sentry).
    });
    

Configuration Quirks

  • Disable Globally: Set enabled: false in config to disable async dispatch entirely (useful for testing).
  • Custom Event Namespaces: The bundle uses Symfony’s event system. Ensure your event classes are autoloaded and follow PSR-4 standards.

Extension Points

  1. Custom Dispatcher: Implement AsyncDispatcherInterface to replace the default behavior:

    class CustomAsyncDispatcher implements AsyncDispatcherInterface {
        public function dispatch($event, $eventName = null, $priority = 0) {
            // Custom logic (e.g., database queue).
        }
        // ... other methods
    }
    

    Register it as a service:

    services:
        async_dispatcher:
            class: App\Service\CustomAsyncDispatcher
    
  2. Pre-Terminate Dispatch: Trigger async events before terminate by listening to KernelEvents::TERMINATE and calling:

    $asyncDispatcher->dispatchNow(); // Dispatches all queued events immediately.
    
  3. Event Filters: Add a filter to exclude certain events:

    $asyncDispatcher->addFilter(function ($event) {
        return !str_starts_with($event->getName(), 'system.');
    });
    
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.
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
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle