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

Pubsub Swarrot Bundle Laravel Package

dekalee/pubsub-swarrot-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dekalee/pubsub-swarrot-bundle
    

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

    Dekalee\PubSubSwarrotBundle\DekaleePubSubSwarrotBundle::class,
    
  2. Configure: Add to config/swarrot.php (or config.yml if using legacy config):

    swarrot:
        provider: pub_sub
        default_connection: pub_sub
        connections:
            pub_sub:
                host: 'noneRequired'  # Placeholder; actual config depends on your pub/sub system (e.g., Redis, RabbitMQ)
    
  3. First Use Case: Publish a message via a Swarrot event:

    use Swarrot\Event\Event;
    
    // Dispatch an event (e.g., in a controller or service)
    $event = new Event('user.created', ['user_id' => 123]);
    $this->get('swarrot')->dispatch($event);
    

    Subscribe to the event in a listener:

    use Dekalee\PubSubSwarrotBundle\Subscriber\PubSubSubscriber;
    
    class UserCreatedSubscriber extends PubSubSubscriber
    {
        public function onUserCreated(Event $event)
        {
            // Handle the event
        }
    
        protected function getSubscribedEvents()
        {
            return [
                'user.created' => 'onUserCreated',
            ];
        }
    }
    

    Register the subscriber in config/swarrot.php:

    swarrot:
        subscribers:
            - App\Subscriber\UserCreatedSubscriber
    

Implementation Patterns

Core Workflows

  1. Event-Driven Architecture:

    • Use Swarrot’s event system to decouple components. Publish events (e.g., order.placed) and let subscribers (e.g., analytics, notifications) react.
    • Example: Trigger a pub/sub message when an order is created:
      $event = new Event('order.placed', ['order_id' => $order->id]);
      $this->get('swarrot')->dispatch($event);
      
  2. Connection Management:

    • Configure multiple pub/sub connections (e.g., Redis for dev, RabbitMQ for prod) in config/swarrot.php:
      connections:
          redis:
              host: 'redis://localhost:6379'
          rabbitmq:
              host: 'amqp://user:pass@rabbitmq:5672'
      
    • Switch connections dynamically:
      $this->get('swarrot')->setConnection('rabbitmq')->dispatch($event);
      
  3. Subscriber Patterns:

    • Service-Based Subscribers: Inject dependencies into subscribers:
      class NotificationSubscriber extends PubSubSubscriber
      {
          private $notifier;
      
          public function __construct(Notifier $notifier)
          {
              $this->notifier = $notifier;
          }
      
          public function onOrderPlaced(Event $event)
          {
              $this->notifier->send('Order #'.$event->getData()['order_id'].' placed!');
          }
      }
      
    • Priority Handling: Use Swarrot’s priority system to order subscriber execution:
      subscribers:
          - { id: 'high_priority', class: App\Subscriber\HighPrioritySubscriber, priority: 10 }
          - { id: 'low_priority', class: App\Subscriber\LowPrioritySubscriber, priority: -10 }
      
  4. Error Handling:

    • Wrap pub/sub operations in try-catch blocks to handle connection issues:
      try {
          $this->get('swarrot')->dispatch($event);
      } catch (PubSubException $e) {
          Log::error('PubSub failed: '.$e->getMessage());
          // Retry or fallback logic
      }
      
  5. Testing:

    • Mock the pub/sub connection in tests using Swarrot’s test utilities:
      $this->get('swarrot')->setConnection('test'); // Assume 'test' is a mock connection
      

Gotchas and Tips

Pitfalls

  1. Connection Configuration:

    • The host: 'noneRequired' in the default config is misleading. Replace it with your actual pub/sub system’s connection string (e.g., Redis, RabbitMQ, or AWS SQS).
    • Example for Redis:
      connections:
          pub_sub:
              host: 'redis://127.0.0.1:6379/0'
      
  2. Subscriber Registration:

    • Subscribers must extend Dekalee\PubSubSwarrotBundle\Subscriber\PubSubSubscriber (or implement its interface). Forgetting this will cause silent failures.
    • Ensure subscribers are registered in config/swarrot.php under the subscribers key.
  3. Event Serialization:

    • Events are serialized before being published. Ensure your event data is serializable (avoid closures, resources, or non-JSON-serializable objects).
    • For complex objects, implement __serialize() and __unserialize() or use JsonSerializable.
  4. Performance:

    • Pub/sub systems may introduce latency. Avoid blocking operations in subscribers (e.g., sync database calls). Use async queues or batch processing where possible.
    • Monitor connection health and implement retries for transient failures.
  5. Debugging:

    • Enable Swarrot’s debug mode to log dispatched events:
      swarrot:
          debug: true
      
    • Check the pub/sub system’s logs (e.g., Redis CLI, RabbitMQ management UI) for dropped messages.
  6. Bundle Maturity:

    • The package has 0 stars and no visible community. Test thoroughly in a staging environment before production use.
    • The SwarrotBundle dependency may introduce additional configuration quirks. Refer to its documentation.

Tips

  1. Environment-Specific Configs: Use Laravel’s environment configs to manage pub/sub connections per environment:

    # config/swarrot.php
    connections:
        pub_sub: '%env(SWARROT_PUBSUB_CONNECTION)%'
    
    # .env
    SWARROT_PUBSUB_CONNECTION=redis://localhost:6379/0
    
  2. Event Namespacing: Prefix event names to avoid collisions (e.g., app.user.created instead of user.created).

  3. Middleware for Events: Use Swarrot’s middleware to preprocess events (e.g., logging, validation):

    class LogEventMiddleware implements EventMiddlewareInterface
    {
        public function handle(Event $event, callable $next)
        {
            Log::debug('Event dispatched: '.$event->getName());
            return $next($event);
        }
    }
    

    Register in config/swarrot.php:

    swarrot:
        middleware:
            - App\Middleware\LogEventMiddleware
    
  4. Extending the Bundle:

    • Override the default PubSubProvider by binding your own implementation in a service provider:
      $this->app->bind(
          \Swarrot\Provider\ProviderInterface::class,
          \App\Provider\CustomPubSubProvider::class
      );
      
    • Extend the PubSubSubscriber class to add custom pub/sub logic (e.g., message transformation).
  5. Monitoring: Integrate with Laravel Horizon or similar tools to monitor pub/sub activity (e.g., message rates, failures).

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.
terminal42/code-quality-tools
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