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

Nats Php Bundle Laravel Package

elandlord/nats-php-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require elandlord/nats-php-bundle
    

    Ensure elandlord/nats-php-bundle is registered in config/bundles.php.

  2. Configure NATS Connection Add NATS settings to .env:

    NATS_URL=nats://localhost:4222
    NATS_USER=  # Optional
    NATS_PASS=  # Optional
    

    Publish the default config:

    php bin/console config:dump-reference elandlord_nats
    
  3. First Use Case: Sending a Message Create a Symfony Messenger message class:

    // src/Message/ExampleMessage.php
    namespace App\Message;
    
    class ExampleMessage {
        public string $content;
    }
    

    Send it via Messenger:

    use App\Message\ExampleMessage;
    use Symfony\Component\Messenger\MessageBusInterface;
    
    public function __construct(private MessageBusInterface $bus) {}
    
    public function sendExample(): void {
        $this->bus->dispatch(new ExampleMessage('Hello NATS!'));
    }
    
  4. Verify NATS Integration Check NATS server logs or use a client like nats-cli to confirm messages are published.


Implementation Patterns

Core Workflows

1. Message Production

  • Symfony Messenger Integration: Leverage Symfony’s built-in Messenger component for dispatching messages. The bundle automatically routes messages to NATS.
    $this->bus->dispatch(new MyMessage($payload));
    
  • Async Transport: Configure NATS as an async transport in config/packages/messenger.yaml:
    messenger:
        transports:
            nats:
                dsn: '%env(NATS_URL)%'
                options:
                    user: '%env(NATS_USER)%'
                    pass: '%env(NATS_PASS)%'
    
  • Serialization: Defaults to Symfony’s serializer component. Customize via messenger.transport.nats.options.serializer.

2. Message Consumption

  • Worker Setup: Define a worker command to process messages:
    # config/packages/messenger.yaml
    messenger:
        workers:
            nats_worker:
                transport: nats
                retry_strategy:
                    max_retries: 3
                    delay: 1000
    
    Run the worker:
    php bin/console messenger:consume nats_worker -vv
    
  • Handler Registration: Create a message handler:
    // src/MessageHandler/ExampleHandler.php
    namespace App\MessageHandler;
    
    use App\Message\ExampleMessage;
    use Symfony\Component\Messenger\Attribute\AsMessageHandler;
    
    #[AsMessageHandler]
    class ExampleHandler {
        public function __invoke(ExampleMessage $message) {
            // Process $message->content
        }
    }
    

3. Request-Reply Pattern

  • Use NATS’ request/response mechanism via custom handlers:
    use Elandlord\NatsBundle\Messenger\Transport\NatsTransport;
    
    $transport = $this->container->get(NatsTransport::class);
    $response = $transport->request('reply.subject', new RequestMessage($data));
    

4. JetStream Integration (Advanced)

  • Enable JetStream in messenger.yaml:
    messenger:
        transports:
            nats:
                options:
                    use_jetstream: true
                    stream_name: my_stream
    
  • Configure persistence for reliability.

Integration Tips

Dependency Injection

  • Access the NATS connection directly:
    use Elandlord\NatsBundle\Nats\NatsConnection;
    
    public function __construct(private NatsConnection $nats) {}
    
    public function publishRaw(): void {
        $this->nats->publish('subject', 'raw payload');
    }
    

Middleware

  • Add NATS-specific middleware (e.g., logging, auth):
    messenger:
        transports:
            nats:
                options:
                    middleware:
                        - App\Middleware\NatsLoggingMiddleware
    

Testing

  • Mock NATS in tests using League\Container or Symfony’s TestContainer:
    use Elandlord\NatsBundle\Tests\MockNatsConnection;
    
    $container->set(NatsConnection::class, MockNatsConnection::class);
    

Gotchas and Tips

Pitfalls

1. Connection Management

  • Issue: NATS connections may hang if not closed properly. Fix: Use dependency injection for NatsConnection (auto-managed by Symfony). Avoid manual new NatsConnection().
  • Debugging: Check for ConnectionException in logs if messages fail silently.

2. Serialization Errors

  • Issue: Custom objects may not serialize/deserialize correctly. Fix: Implement JsonSerializable or configure a custom serializer:
    messenger:
        transports:
            nats:
                options:
                    serializer: App\Serializer\CustomSerializer
    

3. JetStream Quirks

  • Issue: JetStream streams/subscriptions may not auto-create. Fix: Explicitly configure stream_name and subject in messenger.yaml:
    options:
        use_jetstream: true
        stream_name: my_stream
        subject: my.subject
    

4. Retry Logic

  • Issue: Messages may retry indefinitely without visibility. Fix: Configure retry limits in messenger.yaml:
    retry_strategy:
        max_retries: 3
        delay: 1000
        multiplier: 2
    

5. Subject Naming

  • Issue: Collisions or unclear subject naming. Tip: Use namespaced subjects (e.g., app.events.user.created) and document them.

Debugging Tips

Logging

  • Enable NATS transport logging:
    messenger:
        transports:
            nats:
                options:
                    logger: true
    
  • Check Symfony’s monolog channel for NATS events.

NATS CLI Tools

  • Use nats-cli to inspect subjects, streams, and connections:
    nats-cli list subjects
    nats-cli consume my.subject
    

Common Errors

Error Cause Solution
Connection refused NATS server unreachable Verify NATS_URL and server status.
Serialization failure Invalid payload format Check message class implements JsonSerializable.
Stream not found JetStream misconfiguration Ensure stream_name is correct.
Message timeout Slow handler Increase messenger.transport.nats.timeout.

Extension Points

Custom Transports

  • Extend NatsTransport for custom behavior:
    use Elandlord\NatsBundle\Messenger\Transport\NatsTransport;
    
    class CustomNatsTransport extends NatsTransport {
        protected function doSend(): void {
            // Custom logic
        }
    }
    
    Register it in config/packages/messenger.yaml:
    transports:
        custom_nats:
            dsn: '%env(NATS_URL)%'
            class: App\Transport\CustomNatsTransport
    

Event Subscribers

  • Subscribe to NATS events (e.g., connection status):
    use Elandlord\NatsBundle\Event\NatsConnectedEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class NatsSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents(): array {
            return [
                NatsConnectedEvent::class => 'onNatsConnected',
            ];
        }
    
        public function onNatsConnected(NatsConnectedEvent $event): void {
            // Handle connection
        }
    }
    

Middleware

  • Add pre/post-send middleware:
    use Elandlord\NatsBundle\Messenger\Middleware\MiddlewareInterface;
    
    class LoggingMiddleware implements MiddlewareInterface {
        public function handle(Envelope $envelope, StackInterface $stack): Envelope {
            // Log before/after
            return $stack->next($envelope);
        }
    }
    
    Register in messenger.yaml:
    messenger:
        transports:
            nats:
                options:
                    middleware:
                        - App\Middleware\LoggingMiddleware
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai