Skip to content

Commit 187f63f

Browse files
committed
[Messenger] HandlerArgumentsStamp
1 parent 5ec30fa commit 187f63f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

messenger.rst

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2413,6 +2413,62 @@ of the process. For each, the event class is the event name:
24132413
* :class:`Symfony\\Component\\Messenger\\Event\\WorkerRunningEvent`
24142414
* :class:`Symfony\\Component\\Messenger\\Event\\WorkerStoppedEvent`
24152415

2416+
Additional Handler Arguments
2417+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2418+
2419+
It's possible to have messenger pass additional data to the message handler using the
2420+
:class:`Symfony\\Component\\Messenger\\Stamp\\HandlerArgumentsStamp`. Add this stamp to
2421+
the envelope in a middleware and fill it with any additional data you want to have
2422+
available in the handler.
2423+
2424+
// src/Library/Messenger/AdditionalArgumentMiddleware.php
2425+
namespace App\Library\Messenger;
2426+
2427+
use Symfony\Component\Messenger\Envelope;
2428+
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
2429+
use Symfony\Component\Messenger\Middleware\StackInterface;
2430+
use Symfony\Component\Messenger\Stamp\HandlerArgumentsStamp;
2431+
2432+
class AdditionalArgumentMiddleware implements MiddlewareInterface
2433+
{
2434+
public function handle(Envelope $envelope, StackInterface $stack): Envelope
2435+
{
2436+
$envelope = $envelope->with(
2437+
new HandlerArgumentsStamp(
2438+
[
2439+
$this->resolveAdditionalArgument($envelope->getMessage()),
2440+
],
2441+
),
2442+
)
2443+
2444+
return $stack->next()->handle($envelope, $stack);
2445+
}
2446+
2447+
private function resolveAdditionalArgument(object $message): mixed
2448+
{
2449+
// ...
2450+
}
2451+
}
2452+
2453+
Then your handler will look like this:
2454+
2455+
// src/MessageHandler/SmsNotificationHandler.php
2456+
namespace App\MessageHandler;
2457+
2458+
use App\Message\SmsNotification;
2459+
2460+
class SmsNotificationHandler
2461+
{
2462+
public function __invoke(SmsNotification $message, mixed $additionalArgument)
2463+
{
2464+
// ...
2465+
}
2466+
}
2467+
2468+
.. versionadded:: 6.2
2469+
2470+
The HandlerArgumentsStamp was introduced in Symfony 6.2.
2471+
24162472
Multiple Buses, Command & Event Buses
24172473
-------------------------------------
24182474

0 commit comments

Comments
 (0)