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

<?php
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()
    {
 
        $this
            ->setName('littleweb:newsletter')
            ->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!

<?php
 
    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)) {
            return;
        }    
        $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

<?php
// 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...

11 Responses

  1. cordoval says:

    nice man you gave me so much ideas, now I know or at least have an idea how to override the behat colors for instance. Nice article!

    The other idea that i had was how to parse the output with regex and output or exit or return the fail or pass for the command, since usually is this that we use for testing etc. And other systems can read the result and output just the part that we need to display from the error output to do more processing with it…. nice!

    enable subscription mode/ notification via email, it is just a plugin away

    Keep the great work!

  2. cordoval says:

    if you respond email me back as i probably will not see this again

  3. Edge says:

    can I use the command for a Linux based Cron job? if yes how can I do that? trying many ways but couldn’t find one!

    please help!

  4. Ricard Clau says:

    To add this as a Cron job, the command should just be:

    php [path_to_symfony2]/app/console littleweb:newsletter

    and that would be it!

    Please take into account that to execute these commands in a prod environment you should use

    php [path_to_symfony2]/app/console littleweb:newsletter –env=prod

    Otherwise, your command would be executed with development configuration!

  5. Edge says:

    Damn, that was great!! It worked like piece of cake! Thanks man!

  6. Edge says:

    Ricard,

    I’m having troubles on installing Symfony2 on production environment, getting an error message about preg_replace(), you can check it here:

    http://107.22.226.32/Symfony/web/app_dev.php/demo/hello/Ricard

    please let me know if you could help in this regard!

  7. Ricard Clau says:

    This error happens sometimes when there is some YAML mistake.

    Check your prod.yml and test it locally using http://website.local/app.php/demo/hello/whatever and see if same thing happens

    Also note that you should not use app_dev.php in production environments, otherwise it will send a 403 Forbidden header

  8. Edge says:

    when I test it locally using:
    http://localhost/myProject/web/app.php/hello

    that doesn’t show anything, even there is no page source code in View Code from browser.

    when I use it like:
    http://localhost/myProject/app.php/hello

    without adding /web/ directory, I get 404 page error

    I didn’t make any change at all, its just a fresh copy. Any idea how to resolve it?

  9. Ricard Clau says:

    Without seeing it, it is kind of difficult, check app/logs/prod.log maybe you will find some more info on the error there

  10. Edge says:

    do you know any good tutorial to start with? where i can start from scratch about how to release application for production environment?
    I tried but couldn’t really find one, unfortunately.

  11. Ricard Clau says:

    Not really, but it should not be any problem deploying.

    My best advice would be to always test in devel environment with production settings (except the database and that stuff). If you don’t see anything on app/logs or your php error.log I don’t know what can be, sorry