Console commands separation in Symfony
If you are using Symfony for your development, then you are well aware of bin/console
command, that allows you to run commands registered in your application. You probably also add your own commands there to be used e.g. in cron jobs.
What I found annoying is that, in the same console script, I have access to application related commands (like e.g. adding new user) and infrastructure related commands (like e.g. running doctrine migrations).
I wanted to have place where I will access only those application-related. And it turned out pretty easy to do. Here it is how it can be done:
bin/console
internally uses Symfony\Bundle\FrameworkBundle\Console\Application
class which (in coop with Symfony\Component\Console\Application
) is handling all of the work. We need to replace it with our implementation.
Lets create src/Console/Application.php
file with the following content:
As you can see, here lies all the magic. We are interfering with add(Command $command)
method and we filter out unwanted commands. In this case we only leave ones that name starts with app
namespace.
If you don’t want to base this on command’s name, you can easily “tag” your commands with some interface and make use of
instanceof
here.
Only left to do, is to copy bin/console
file to e.g. bin/application
and change imports part so our implementation is used.
So in bin/application
lets change:
use Symfony\Bundle\FrameworkBundle\Console\Application
into:
use App\Console\Application
And that’s it! You can now run bin/application
to see only your commands: