Add middleware

Overview

In this guide you'll learn how to add a custom middleware.
A middleware is called when the message bus dispatches messages. The middleware defines what happens when you dispatch a message. For example the send_message middleware is responsible for sending your message to the configured transport and the handle_message middleware will actually call your handlers for the given message.

Prerequisites

As most guides, this guide is also built upon the Plugin base guide, but you don't necessarily need that. Furthermore, registering classes or services to the DI container is also not explained here, but it's covered in our guide about Dependency injection, so having this open in another tab won't hurt.

Create middleware

First we need to create a new service that implements the MiddlewareInterface. This interface comes with a method handle, which should always call the next middleware.
<plugin root>/src/MessageQueue/Middleware/ExampleMiddleware.php
1
<?php declare(strict_types=1);
2
3
namespace Swag\BasicExample\MessageQueue\Middleware;
4
5
use Symfony\Component\Messenger\Envelope;
6
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
7
use Symfony\Component\Messenger\Middleware\StackInterface;
8
9
class ExampleMiddleware implements MiddlewareInterface
10
{
11
public function handle(Envelope $envelope, StackInterface $stack): Envelope
12
{
13
// do something here
14
15
// don't forget to call the next middleware
16
return $stack->next()->handle($envelope, $stack);
17
}
18
}
Copied!

Configure middleware

After we've created our middleware, we have to add that middleware to the message bus through configuration.
For each defined bus in our framework.yaml, we can define the middleware that this bus should use. To add middleware, we simply specify our custom middleware as follows:
<platform root>/src/Core/Framework/Resources/config/packages/framework.yaml
1
framework:
2
messenger:
3
default_bus: messenger.bus.shopware
4
buses:
5
messenger.bus.shopware:
6
middleware:
7
- 'Swag\BasicExample\MessageQueue\Middleware\ExampleMiddleware'
8
- 'Swag\BasicExample\MessageQueue\Middleware\AnotherExampleMiddleware'
Copied!

More interesting topics