How to cancel dispatched message in symfony 5?

by wilmer.lemke , in category: PHP Frameworks , 9 months ago

How to cancel dispatched message in symfony 5?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 9 months ago

@wilmer.lemke 

In Symfony 5, you can cancel a dispatched message by using the "envelope" middleware. The envelope middleware allows you to process dispatched messages before they are sent to the handler. Here's how you can cancel a dispatched message:

  1. Create a middleware class that implements the MiddlewareInterface interface. For example, create a MessageCancellationMiddleware class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/Middleware/MessageCancellationMiddleware.php

use SymfonyComponentMessengerMiddlewareMiddlewareInterface;
use SymfonyComponentMessengerMiddlewareMiddlewareStackInterface;
use SymfonyComponentMessengerMiddlewareStackInterface;
use SymfonyComponentMessengerEnvelope;

class MessageCancellationMiddleware implements MiddlewareInterface
{
    public function handle(Envelope $envelope, StackInterface $stack): Envelope
    {
        // Check if the message should be cancelled
        if ($this->shouldCancelMessage($envelope)) {
            // Cancellation logic here
            // You can throw an exception or return null to cancel the message
            throw new Exception('Message cancelled');
        }

        return $stack->next()->handle($envelope, $stack);
    }

    private function shouldCancelMessage(Envelope $envelope): bool
    {
        // Add your own logic to determine if the message should be cancelled
        // For example, you can check the message class or its content
        // If the message should be cancelled, return true; otherwise, return false
    }
}


  1. Register the middleware as a service in your Symfony configuration file (config/services.yaml):
1
2
3
4
5
services:
    ...
    AppMiddlewareMessageCancellationMiddleware:
        tags:
            - { name: messenger.middleware }


  1. Now when you dispatch a message in your application, the handle() method of the MessageCancellationMiddleware class will be called before the message is sent to the handler. Inside the shouldCancelMessage() method, you can add your own logic to determine if the message should be cancelled. If the message should be cancelled, throw an exception or return null to cancel the message.
1
2
// Dispatch a message
$this->dispatchMessage(new MyMessage());


If the message is cancelled, an exception will be thrown and your application can handle it accordingly. If the message is not cancelled, it will be sent to the handler as usual.


Note: Make sure to adjust the shouldCancelMessage() method with your own logic to determine if a message should be cancelled or not.