Maad
Maad

Reputation: 219

How does Symfony Messenger determine which handler should handle each type of message?

I am trying to implement exchanges in rabbit and Symfony, using the Messenger component.

Let's say we've got a transport:

messenger:
    transports:
        amqp_image_resize:
            dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
            options:
                exchange:
                    name: image_resize_ex
                    type: fanout
                queue:
                    name: image_resize_qu

    routing:
         'App\MessageBus\Message\Image\Resize': amqp_image_resize

How does the consumer know which handler should it use to handle the message?

Upvotes: 2

Views: 1417

Answers (1)

yivi
yivi

Reputation: 47629

First, the handler class should implement the Symfony\Component\Messenger\Handler\MessageHandlerInterface.

This allows Symfony to autoconfigure the service with the appropriate tags.

Then your handler should be typehinted to with the type of message it's capable of handling. In your case, something like this:

namespace App\MessageBus\Handler;

use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use App\MessageBus\Message\Image\Resize;

class ResizeHandler implements MessageHandlerInterface {

   public function __invoke(Resize $message) {

      // do your thing
   }

}

The interface plus the parameter type-hint allow Symfony to determine which handler should deal with this message.

This is shown on the docs here.

Upvotes: 3

Related Questions