New in Symfony 6.4: More Built-in Message Handlers

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:

use SymfonyComponentMessengerMessageBusInterface;
use SymfonyComponentProcessMessengerRunProcessMessage;

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:

use SymfonyComponentConsoleMessengerRunCommandMessage;
use SymfonyComponentMessengerMessageBusInterface;

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

public function cleanUp(): void
{
// …

// once handled, it returns a RunCommandMessage 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:

use SymfonyComponentHttpClientMessengerRPingWebhookMessage;
use SymfonyComponentMessengerMessageBusInterface;

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);
}
}

Sponsor the Symfony project.

Symfony Blog

Read More

Latest News

PHP-Releases

PHP 8.3.7 released!

PHP 8.2.19 released!

Generated by Feedzy