Kevin Bond
Contributed by Kevin Bond in #49813 , #49814 and #49815

The Messenger component is designed around two main concepts: messages (which are the classes that hold the data) and handlers (which are the classes called when the message is dispatched).

In Symfony 6.4 we're introducing some new built-in handlers so you can use those features in your applications without having to implement them.

Run Process Handler

This handler creates a new process with the given information and runs it using the Process component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Process\Messenger\RunProcessMessage;

class SomeService
{
    public function __construct(private readonly MessageBusInterface $bus)
    {
    }

    public function cleanUp(): void
    {
        // once handled, it returns a RunProcessContext object with information
        // such as the exit code, the output content, etc.
        $this->bus->dispatch(new RunProcessMessage(
            ['rm', '-rf', 'var/log/temp/*'],
            cwd: '/my/custom/working-dir'
        ));

        // ...
    }
}

Run Command Handler

This handler runs the given command name and arguments as a terminal command using the Console component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\Console\Messenger\RunCommandMessage;
use Symfony\Component\Messenger\MessageBusInterface;

class SomeService
{
    public function __construct(private readonly MessageBusInterface $bus)
    {
    }

    public function cleanUp(): void
    {
        // ...

        // once handled, it returns a RunCommandContext object with information
        // such as the exit code, the output content, etc.
        $this->bus->dispatch(new RunCommandMessage('app:my-cache:clean-up --dir=var/temp'));
        $this->bus->dispatch(new RunCommandMessage('cache:clear'));
    }
}

The RunCommandMessage class defines the $throwOnFailure and $catchExceptions constructor arguments so you can better control what to do when an error happens.

Ping Webhook Handler

This handler pings the given webhook URL using the HttpClient component. Combine it with the Scheduler component to ping the URL repeatedly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use Symfony\Component\HttpClient\Messenger\RPingWebhookMessage;
use Symfony\Component\Messenger\MessageBusInterface;

class SomeService
{
    public function __construct(private readonly MessageBusInterface $bus)
    {
    }

    public function ping(): void
    {
        // An HttpExceptionInterface is thrown on 3xx/4xx/5xx
        $this->bus->dispatch(new PingWebhookMessage('GET', 'https://example.com/status');

        // Ping, but does not throw on 3xx/4xx/5xx
        $this->bus->dispatch(new PingWebhookMessage('GET', 'https://example.com/status', throw: false);
    }
}
Published in #Living on the edge