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

Abstract Bus Event Message Laravel Package

artox-lab/abstract-bus-event-message

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require artox-lab/abstract-bus-event-message
    

    Add the package service provider to config/app.php under providers:

    ArtoxLab\AbstractBusEventMessage\AbstractBusEventMessageServiceProvider::class,
    
  2. First Use Case: Basic Event Dispatching Create a simple event class extending AbstractEvent:

    namespace App\Events;
    
    use ArtoxLab\AbstractBusEventMessage\AbstractEvent;
    
    class UserRegistered extends AbstractEvent
    {
        public function __construct(public string $userId) {}
    }
    

    Dispatch the event in a controller or service:

    use App\Events\UserRegistered;
    
    event(new UserRegistered('user-123'));
    
  3. Where to Look First

    • Abstract Classes: Review AbstractEvent and AbstractCommand in src/AbstractEvent.php and src/AbstractCommand.php for base implementations.
    • Traits: Check HasBusMessage trait for common bus message methods.
    • Service Provider: Inspect AbstractBusEventMessageServiceProvider for bindings and boot logic.

Implementation Patterns

Workflows

  1. Event-Driven Architecture

    • Use AbstractEvent for domain events (e.g., OrderCreated, PaymentProcessed).
    • Subscribe to events via Laravel’s Event::listen or package-specific listeners:
      Event::listen(UserRegistered::class, function ($event) {
          // Handle registration logic
      });
      
  2. Command Bus Integration

    • Extend AbstractCommand for actions (e.g., SendWelcomeEmail).
    • Integrate with Laravel’s Bus facade or a package like spatie/laravel-command-bus:
      use App\Commands\SendWelcomeEmail;
      use Illuminate\Support\Facades\Bus;
      
      Bus::dispatch(new SendWelcomeEmail($userId));
      
  3. Message Validation

    • Leverage Laravel’s FormRequest or Illuminate\Contracts\Validation\Validatable for message validation:
      use Illuminate\Foundation\Http\FormRequest;
      
      class UserRegistered extends AbstractEvent implements Validatable
      {
          public function rules(): array
          {
              return ['userId' => 'required|string'];
          }
      }
      
  4. Middleware for Bus Messages

    • Apply middleware to commands/events using Laravel’s Bus::pipe:
      Bus::pipe([
          \App\Middleware\LogCommand::class,
          \App\Middleware\AuthorizeUser::class,
      ]);
      

Integration Tips

  • Laravel Echo/Pusher: Pair events with real-time updates:
    Event::listen(UserRegistered::class, function ($event) {
        broadcast(new UserRegisteredBroadcast($event->userId));
    });
    
  • Queue Workers: Dispatch events/commands to queues for async processing:
    Bus::dispatchSync(new SendWelcomeEmail($userId))->onQueue('emails');
    
  • Testing: Use Bus::fake() or Event::fake() for unit/feature tests:
    Bus::fake();
    Bus::assertDispatched(SendWelcomeEmail::class);
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies

    • Avoid circular references between events/commands (e.g., EventA dispatches EventB, which dispatches EventA again). Use middleware or guards to prevent infinite loops.
  2. Missing Serialization

    • Ensure all bus messages are serializable (e.g., avoid closures, resources). Use #[Spatie\LaravelData\Data] or Arrayable for complex data:
      use Spatie\LaravelData\Data;
      
      #[Data]
      class UserRegistered extends AbstractEvent { ... }
      
  3. Overuse of Events

    • Events should represent what happened, not how to respond. Decouple event dispatching from handling logic.
  4. Queue Stuck Jobs

    • Monitor failed jobs in failed_jobs table. Use Bus::later() for delayed commands:
      Bus::dispatch(new ProcessOrder)->delay(now()->addMinutes(5));
      

Debugging

  • Log Dispatching: Add a listener to log all bus messages:
    Event::listen('*', function ($event) {
        \Log::debug('Event dispatched', ['event' => get_class($event)]);
    });
    
  • Xdebug: Step through AbstractBusEventMessageServiceProvider to trace bindings.
  • Artisan Commands: Clear cached bindings if issues arise:
    php artisan config:clear
    php artisan cache:clear
    

Extension Points

  1. Custom Metadata Add metadata to messages via traits or interfaces:

    interface HasMetadata
    {
        public function metadata(): array;
    }
    
  2. Dynamic Handlers Use Laravel’s EventServiceProvider to dynamically register listeners:

    protected $listen = [
        UserRegistered::class => [
            'App\Listeners\SendNotification',
            'App\Listeners\UpdateAnalytics',
        ],
    ];
    
  3. Message Retry Logic Implement ShouldQueue interface for retries:

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class ProcessPayment extends AbstractCommand implements ShouldQueue
    {
        use Queueable;
    
        public int $tries = 3;
        public static int $wait = 60; // seconds
    }
    
  4. Policy Integration Attach policies to commands/events for authorization:

    use Illuminate\Auth\Access\HandlesAuthorization;
    
    class SendEmailCommand extends AbstractCommand
    {
        use HandlesAuthorization;
    
        public function authorize()
        {
            return $this->user->can('send-emails');
        }
    }
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor