A forgiving command loader for Symfony Console

This article summaries a solution to the problem of calling and listing commands in Symfony Console when at least one of the commands is not instantiable.

The problem

Ordinarily, this shouldn’t be a problem. After all, classes should be instantiable, shouldn’t they? But, in my work at Funeral Zone, we have a use-case of a console application that sits in multiple microservices. Some of the commands in the application are reliant on environment variables (such as database credentials) that are not necessary for all microservices. This means, on a microservice that doesn’t require a database, the database related commands can’t initialize — and they bring down the rest of the console application with them!

Command loading

$consoleApp = new ConsoleApplication;
$consoleApp->setCommandLoader(
    new ContainerCommandLoader($iocContainer, [
        'command:one' => CommandOne::class,
        'command:two' => ComamndTwo::class,
    ])
));

When the console application executes a command…

php console.php command:one

The CommandOne command will be retrieved from the IoC container. If it fails, this does not stop CommandTwo from being loaded — because the commands are only loaded when executed.

Remaining problem of listing

This Symfony documentation confirms that:

Calling the list command will instantiate all commands, including lazy commands.

The solution to this is what I’ve termed a ‘forgiving command loader’. I’ve published it on GitHub. It requires another CommandLoaderInterface to be injected into it. Then, using the composition principle, it proxies the internal loader. If it encounters an exception when loading a command, it returns a placeholder command. It sets the description of the placeholder command to ‘** Could not load’. This way, you can still list all the commands in your application.

php console.php listAvailable commands:
 command:one    Our first command
 command:two    ** Could not load
 command:three  Our third command
 command:four   Our fourth command

If you try to execute command:two you will receive the exception that was originally caught when loading.

Funeral Zone Engineering

Musings, learnings and sharing from the design and engineering team at Funeral Zone

Chris Harrison

Written by

Software engineer

Funeral Zone Engineering

Musings, learnings and sharing from the design and engineering team at Funeral Zone