2 Methods to Handle Messenger Message in Symfony 8

2 Methods to Handle Messenger Message in Symfony 8

Symfony Messenger is a flexible component designed to decouple message dispatching from message processing. It allows applications to handle events or notifications either synchronously or asynchronously. In order for a message to be processed, Symfony needs to know which handler should react to it. This tutorial provides 2 methods how to handle Messenger message in Symfony 8 application.

First, let's define a message class that represents an SMS notification.

src/Messaging/Message/SmsNotification.php

<?php

namespace App\Messaging\Message;

class SmsNotification
{
    private string $message;

    public function getMessage(): string { return $this->message; }
    public function setMessage(string $message): void { $this->message = $message; }
}

For testing purposes, we dispatching a message from a controller.

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Messaging\Message\SmsNotification;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/')]
    public function index(MessageBusInterface $bus): Response
    {
        $smsNotification = new SmsNotification();
        $smsNotification->setMessage('Hello world');
        $bus->dispatch($smsNotification);

        return new Response();
    }
}

At this point, the message is sent to the Messenger system, but it still needs a handler to process it.

Method 1 - AsMessageHandler attribute

The most modern and recommended approach is to use the AsMessageHandler attribute. Symfony will automatically register the class as a handler when auto-configuration is enabled.

src/Messaging/Handler/SmsNotificationHandler.php

<?php

namespace App\Messaging\Handler;

use App\Messaging\Message\SmsNotification;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class SmsNotificationHandler
{
    public function __invoke(SmsNotification $smsNotification): void
    {
        echo $smsNotification->getMessage();
    }
}

Method 2 - messenger.message_handler tag

If you prefer configuration-based registration, you can manually apply tag messenger.message_handler for the handler in the service container. In this method, the handler class itself does not require any attributes.

config/services.yaml

services:
    # ...
    App\Messaging\Handler\SmsNotificationHandler:
        tags: [messenger.message_handler]

src/Messaging/Handler/SmsNotificationHandler.php

<?php

namespace App\Messaging\Handler;

use App\Messaging\Message\SmsNotification;

class SmsNotificationHandler
{
    public function __invoke(SmsNotification $smsNotification): void
    {
        echo $smsNotification->getMessage();
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.