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

Rabbit Bundle Laravel Package

arthem/rabbit-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require arthem/rabbit-bundle
    
  2. Enable Auto-Tagging Add this to config/services.yaml to auto-tag event handlers:

    services:
        _instanceof:
            Arthem\Bundle\RabbitBundle\Consumer\Event\EventMessageHandlerInterface:
                tags: ['arthem_rabbit.event_handler']
    
  3. First Use Case: Sending a Message Inject the RabbitProducer service and publish a message with a type:

    use Arthem\Bundle\RabbitBundle\Producer\RabbitProducerInterface;
    
    public function __construct(private RabbitProducerInterface $producer) {}
    
    public function publishEvent(string $eventType, array $payload): void
    {
        $this->producer->publish($eventType, $payload);
    }
    
  4. Create a Handler Implement EventMessageHandlerInterface and tag it:

    use Arthem\Bundle\RabbitBundle\Consumer\Event\EventMessageHandlerInterface;
    
    class MyEventHandler implements EventMessageHandlerInterface
    {
        public function handle(string $eventType, array $payload): void
        {
            // Process logic
        }
    
        public function supportedTypes(): array
        {
            return ['my.event.type'];
        }
    }
    

Implementation Patterns

Workflows

  1. Producer-Consumer Flow

    • Producer: Use RabbitProducerInterface to publish messages with a type (e.g., user.created).
    • Consumer: Handlers are auto-discovered via the arthem_rabbit.event_handler tag. The bundle routes messages to the correct handler based on the type.
  2. Queue and Exchange Management

    • The bundle defaults to:
      • Queue: event
      • Direct Exchange: x-event
      • Binding: Queue to exchange with routing key matching the message type.
    • Customize via config/packages/arthem_rabbit.yaml:
      arthem_rabbit:
          queues:
              - name: 'custom_queue'
                exchange: 'x-custom'
                routing_key: 'custom.#'
      
  3. Handling Multiple Message Types

    • A single handler can support multiple types:
      public function supportedTypes(): array
      {
          return ['type1', 'type2'];
      }
      
  4. Asynchronous Processing

    • Use Symfony’s Messenger component alongside this bundle for decoupled processing:
      $this->producer->publish('async.task', ['data' => $payload]);
      

Integration Tips

  • Dependency Injection: Prefer constructor injection for RabbitProducerInterface and handlers.
  • Logging: Use Symfony’s LoggerInterface in handlers for observability:
    use Psr\Log\LoggerInterface;
    
    public function __construct(private LoggerInterface $logger) {}
    
  • Testing: Mock RabbitProducerInterface or use a test RabbitMQ instance (e.g., rabbitmq:3 in Docker).

Gotchas and Tips

Pitfalls

  1. Handler Discovery

    • Forgetting to tag handlers with arthem_rabbit.event_handler will silently ignore them.
    • Fix: Verify tags with:
      bin/console debug:container | grep arthem_rabbit.event_handler
      
  2. Message Type Mismatch

    • If no handler supports a message type, it will be silently dropped.
    • Fix: Log unsupported types in handlers:
      public function handle(string $eventType, array $payload): void
      {
          if (!in_array($eventType, $this->supportedTypes())) {
              $this->logger->warning("Unsupported event type: {$eventType}");
              return;
          }
          // Process...
      }
      
  3. Failure Tracking Overhead

    • Enabling failure: true in config adds Doctrine ORM dependency and database writes.
    • Tip: Disable in production if not needed:
      arthem_rabbit:
          failure: false  # Default
      
  4. RabbitMQ Connection Issues

    • The bundle uses php-amqplib/rabbitmq-bundle under the hood. Ensure your config/packages/rabbitmq.yaml is correctly configured:
      rabbitmq:
          hosts:
              tcp://guest:guest@localhost:5672
      

Debugging

  • Check Consumers: List active consumers:
    bin/console debug:container | grep consumer
    
  • RabbitMQ Management UI: Use the RabbitMQ Web UI to inspect queues/exchanges.
  • Logs: Enable debug mode for the bundle:
    # config/packages/dev/arthem_rabbit.yaml
    arthem_rabbit:
        debug: true
    

Extension Points

  1. Custom Exchanges/Queues Extend the bundle’s configuration to add new queues/exchanges:

    arthem_rabbit:
        queues:
            - name: 'notifications'
              exchange: 'x-notifications'
              routing_key: 'notification.#'
    
  2. Custom Failure Entity Override BaseFailedEvent to add custom fields:

    class CustomFailedEvent extends BaseFailedEvent
    {
        #[ORM\Column(type: 'string', nullable: true)]
        private ?string $customField = null;
    
        // Getters/Setters...
    }
    
  3. Middleware for Handlers Use Symfony’s middleware pattern to pre/post-process messages:

    use Symfony\Component\HttpKernel\Middleware\MiddlewareInterface;
    
    class LogHandlerMiddleware implements MiddlewareInterface
    {
        public function handle(Request $request, callable $next): Response
        {
            // Log before/after handler execution
            return $next($request);
        }
    }
    
  4. Retry Logic Implement retry logic in handlers using a decorator pattern:

    class RetryHandlerDecorator implements EventMessageHandlerInterface
    {
        public function __construct(private EventMessageHandlerInterface $handler) {}
    
        public function handle(string $eventType, array $payload): void
        {
            try {
                $this->handler->handle($eventType, $payload);
            } catch (Exception $e) {
                // Retry logic...
            }
        }
    
        public function supportedTypes(): array
        {
            return $this->handler->supportedTypes();
        }
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware