How to create a new Console Command in Symfony2

Is is true that Symfony2 Console Component was one of the most stable parts of the framework and many people have already been using it for several months in many projects as it makes it really easy to develop this kind of software. And of course, everything is done in a really cool way, as many of the parts of Symfony2.

Thanks to this component we can really say Bye Bye to our old unfriendly PHP Cron interfaces and start nice coloring in our outputs!
Let’s see how can extremely easy create a new Command Task and custom our output.

1) Create a file in Command Folder, for instance NewsletterCommand.php and fill it with an empty Command structure as follows

namespace Ricardclau\LittlewebBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class NewsletterCommand extends ContainerAwareCommand
    protected function configure()
            ->setDescription('Sends our daily newsletter to our registered users')
    protected function execute(InputInterface $input, OutputInterface $output)
        $output->writeln('Starting Newsletter process');

At this point, we have already created a new Console Command which actually doesn’t do much (Just displays a message) but it already appears in php app/console command list joining other existing commands like the Doctrine2 ones which most of one might be used to use to create new Entities.

You might have noticed that our brand new Command extends from ContainerAwareCommand with brigns us the magic Symfony2 container object to be used in our console tasks.

And if we execute “php app/console littleweb:newsletter” we will se the output ‘Starting newsletter process’.

2) Coloring the output

It is so much fun to see that Fabien Potencier and the rest of the Symfony2 crew have though about everything, even helpers to colour our output.
By default, Symfony2 provides us with 4 helpers: error, info, comment and question. Let’s see how can use them!

    protected function execute(InputInterface $input, OutputInterface $output)
        $dialog = $this->getHelperSet()->get('dialog');
        if (!$dialog->askConfirmation($output, '<question>Do you confirm spamming our users?</question>', false)) {
        $output->writeln('<comment>Starting Newsletter process</comment>');       
        $output->writeln('<info>Newsletter process ended succesfully</info>');

If we re-run our littleweb:newsletter command we will see some nice colored output.
Error formatting helper is automatically used whenever an Exception arises, but can also use it in our command.

3) Creating our own formatting helper

I am a big FC Barcelona supporter, so lets create a coloring tag with blue in the background and red in the foreground

// New use on top of file
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
// Inside execute function
$output->getFormatter()->setStyle('fcbarcelona', new OutputFormatterStyle('red', 'blue', array('blink', 'bold', 'underscore')));
$output->writeln('<fcbarcelona>Messi for the win</fcbarcelona>');

Notice that there is a 3rd parameter which allows us to do even cooler things. By the way, I haven’t been able to make blink work in my Ubuntu systems. Does anyone have an idea on which SOs is this supported?

Of course, you can for sure get better styling than me using other colors 😉

4) And once coloring is done we can code our command. One of the nice things in Symfony2 is that all components get connected through the magic Container object so we can use other services we might have defined in other bundles, like Doctrine or even our own ones.

There are many other options like prompting to user, set default values, etc… which is really well explained in this Symfony2 cookbook. There are even examples on how to regexp test our outputs.

As you can see, it is really easy and cool to create Console Commands in Symfony2, so let’s hope this small post is useful to someone!

And after this small post, next one will cover AsseticBundle inside LittleWeb project as promised. Stay tuned!

You may also like...