How to improve your Symfony commands

November 17, 2020

When we develop a Symfony project, we inherit a lot of default commands. For example, if we create a new project starting from symfony/website-skeleton, we already have more than 80 commands. We can prefix all our custom commands with app: so that they don’t get mixed up, but the display remains somewhat overloaded.

I’m going to present some of the tricks I configure on most of my Symfony projects.

The main one consists of creating a new default command that will allow us to filter what is displayed via the bin/console instruction so that there are only our custom commands. Don’t worry! The bin/console list behaviour will not change to let us see all available commands.

Initialization

To illustrate this post, we will generate a new Symfony project using website-skeleton.

Default command

Let’s start by creating our new default command: src/Command/DefaultCommand.php. In addition to the usual elements, we explicitly state that this is a hidden command that will not appear in the lists.

The execute method will probably be a bit different from the one you are used to writing since we will use an already existing command: list. Therefore, we are also going to add an extra parameter to it, the one that allows us to display only our custom commands.

Custom application

To invoke this new command when you write bin/console, you will need to configure the application default command. There are two ways to achieve this.

You can edit the bin/console file to add the default command statement.

You can also create your own Application class and instantiate it instead of the Symfony class, still within the bin/console file.

I prefer this second option. It may be more verbose, but it allows for more customizations in addition to the default command.

Here is a complete example with all these customizations.

Conclusion

It is not for nothing that Symfony Console is the most downloaded Symfony component. It is both powerful and straightforward to configure. I hope that this article will have taught you at least a little bit about it.