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

Messagebus Bundle Laravel Package

bobrd/messagebus-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require bobrd/messagebus-bundle
    

    Register the bundle in config/app.php under providers:

    BobrD\MessageBusBundle\MessageBusServiceProvider::class,
    
  2. Basic Configuration Publish the default config:

    php artisan vendor:publish --provider="BobrD\MessageBusBundle\MessageBusServiceProvider" --tag="config"
    

    Edit config/messagebus.php to define your bus (e.g., sync, async, or custom).

  3. First Use Case: Sending a Message Define a message class (e.g., app/Events/MessageSent.php):

    namespace App\Events;
    
    class MessageSent {
        public function __construct(public string $content) {}
    }
    

    Dispatch it via the bus:

    use BobrD\MessageBusBundle\MessageBus;
    
    $bus = app(MessageBus::class);
    $bus->dispatch(new MessageSent('Hello, Bus!'));
    
  4. Handling Messages Register a handler (e.g., app/Handlers/MessageSentHandler.php):

    namespace App\Handlers;
    
    use App\Events\MessageSent;
    
    class MessageSentHandler {
        public function __invoke(MessageSent $message) {
            // Handle the message
        }
    }
    

    Bind the handler in a service provider:

    $this->app->bind(MessageSent::class, function () {
        return new MessageSentHandler();
    });
    

Implementation Patterns

Core Workflows

  1. Synchronous Bus Use the default sync bus for immediate processing:

    $bus = app(MessageBus::class)->bus('sync');
    $bus->dispatch(new MessageSent('Sync message'));
    
  2. Asynchronous Bus Configure an async bus (e.g., with queue driver) in config/messagebus.php:

    'buses' => [
        'async' => [
            'driver' => 'queue',
            'queue'  => 'messagebus',
        ],
    ],
    

    Dispatch messages to the async bus:

    $bus->bus('async')->dispatch(new MessageSent('Async message'));
    
  3. Middleware Integration Attach middleware to buses (e.g., logging or validation):

    $bus->bus('sync')->pipe(function ($message, callable $next) {
        logger()->info("Processing: " . get_class($message));
        return $next($message);
    });
    
  4. Message Prioritization Use queue priorities (if using queue driver) by extending the message class:

    class HighPriorityMessageSent extends MessageSent {
        public function getPriority(): int { return 10; }
    }
    

Integration Tips

  • Laravel Events Bridge message bus to Laravel events for compatibility:
    $bus->dispatch(new MessageSent('Event'));
    event(new \App\Events\MessageSentEvent('Event'));
    
  • Testing Mock the bus in tests:
    $bus = Mockery::mock(MessageBus::class);
    $bus->shouldReceive('dispatch')->once();
    
  • Custom Drivers Extend \BobrD\MessageBusBundle\Contracts\Bus to create custom transport layers (e.g., Kafka, RabbitMQ).

Gotchas and Tips

Pitfalls

  1. Handler Binding

    • Issue: Handlers not invoked if not bound to the message class.
    • Fix: Ensure handlers are bound in a service provider or use autowiring (Laravel 8+):
      $this->app->bind(MessageSent::class, MessageSentHandler::class);
      
  2. Async Bus Configuration

    • Issue: Async messages may fail silently if the queue driver is misconfigured.
    • Fix: Verify config/queue.php and run:
      php artisan queue:work
      
  3. Circular Dependencies

    • Issue: Handlers depending on the bus can cause circular resolution.
    • Fix: Use dependency injection carefully or resolve the bus via app():
      $bus = app(MessageBus::class);
      
  4. Message Serialization

    • Issue: Complex objects may not serialize properly for async buses.
    • Fix: Implement __serialize()/__unserialize() or use shouldBeSerializable trait.

Debugging

  • Log Middleware Add logging middleware to trace message flow:
    $bus->pipe(function ($message, callable $next) {
        logger()->debug("Message: " . json_encode($message));
        return $next($message);
    });
    
  • Queue Monitoring For async buses, monitor queues with:
    php artisan queue:failed-table
    php artisan queue:work --once --sleep=3 --tries=1
    

Extension Points

  1. Custom Bus Drivers Implement \BobrD\MessageBusBundle\Contracts\Bus to add support for new transports (e.g., gRPC, WebSockets).

  2. Message Metadata Attach metadata to messages via a Metadata interface:

    interface Metadata {
        public function getHeaders(): array;
    }
    

    Access headers in handlers:

    $message->getHeaders()['custom_key'] ?? null;
    
  3. Retry Logic Extend the async bus to support retries:

    'async' => [
        'driver' => 'queue',
        'tries'  => 3,
    ],
    
  4. Message Validation Use Laravel Validation middleware:

    $bus->pipe(function ($message, callable $next) {
        $validator = Validator::make($message, ['content' => 'required']);
        if ($validator->fails()) {
            throw new \InvalidArgumentException($validator->errors()->first());
        }
        return $next($message);
    });
    
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings