Skip to content

[Messenger] HandlerArgumentsStamp #17174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions messenger.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2513,6 +2513,59 @@ of the process. For each, the event class is the event name:

The ``WorkerRateLimitedEvent`` was introduced in Symfony 6.2.

Additional Handler Arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It's possible to have messenger pass additional data to the message handler
using the :class:`Symfony\\Component\\Messenger\\Stamp\\HandlerArgumentsStamp`.
Add this stamp to the envelope in a middleware and fill it with any additional
data you want to have available in the handler::

// src/Messenger/AdditionalArgumentMiddleware.php
namespace App\Messenger;

use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Stamp\HandlerArgumentsStamp;

final class AdditionalArgumentMiddleware implements MiddlewareInterface
{
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$envelope = $envelope->with(new HandlerArgumentsStamp([
$this->resolveAdditionalArgument($envelope->getMessage()),
]));

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

private function resolveAdditionalArgument(object $message): mixed
{
// ...
}
}

Then your handler will look like this::

// src/MessageHandler/SmsNotificationHandler.php
namespace App\MessageHandler;

use App\Message\SmsNotification;

class SmsNotificationHandler
{
public function __invoke(SmsNotification $message, mixed $additionalArgument)
{
// ...
}
}

.. versionadded:: 6.2

The :class:`Symfony\\Component\\Messenger\\Stamp\\HandlerArgumentsStamp`
was introduced in Symfony 6.2.

Multiple Buses, Command & Event Buses
-------------------------------------

Expand Down