@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 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 2 3 4 5 |
services: ... AppMiddlewareMessageCancellationMiddleware: tags: - { name: messenger.middleware } |
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.