Feature: #101700 - Use Symfony attribute to autoconfigure message handlers¶
See forge#101700
Description¶
The symfony PHP attribute \Symfony\Component\Messenger\Attribute\AsMessageHandler
is now respected and allows to register services as message handlers by setting
the attribute on the class or the method.
Before:
MyVendor\MyExtension\Queue\Handler\DemoHandler:
tags:
- name: 'messenger.message_handler'
After:
The registration can be removed from the Configuration/Services.yaml
file and the attribute is assigned to the handler class instead:
<?php
namespace MyVendor\MyExtension\Queue\Handler;
use MyVendor\MyExtension\Queue\Message\DemoMessage;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
final class DemoHandler
{
public function __invoke(DemoMessage $message): void
{
// do something with $message
}
}
It's also possible to set the attribute on the method:
<?php
namespace MyVendor\MyExtension\Queue\Handler;
use MyVendor\MyExtension\Queue\Message\DemoMessage;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
final class DemoHandler
{
#[AsMessageHandler]
public function __invoke(DemoMessage $message): void
{
// do something with $message
}
}
Impact¶
The registration of services as message handlers has been simplified by
respecting the \Symfony\Component\Messenger\Attribute\AsMessageHandler
attribute. When using this attribute, there is no need to register such
service in the Configuration/Services.yaml
file anymore. Existing
configuration will work as before.