# Creating a Symfony2 Console Command

By Steve Francia · June 20, 2011 · https://spf13.com/post/creating-a-symfony2-console-command/


<figure >
    
    
    
    
      
    

    
      
      <img src="/post/creating-a-symfony2-console-command/symfony_ss.png" loading="lazy" decoding="async" width="960" height="350" alt="symfony" />
      
    
    
</figure>


One of the weaknesses of PHP as a languages has always been it’s ability
to write proper command line utilities. Yes PHP is pretty much built to
drive the web, and it does that rather well, but there are plenty of
reasons to want to be able to write a program that is callable from the
command line that interfaces with your web app. Symfony2 does a rather
good job at providing a nice toolset to build command line applications
in php.

First you need a bundle. See [creating a Symfony2
bundle](/post/creating-your-own-symfony2-bundle "Creating your own Symfony2 Bundle").

Creating your command line application
--------------------------------------

Create a directory in your bundle top level called Command

    mkdir steveBundle/Command

Create a class in that directory that ends in Command.php like
yoCommand.php

Populate the file with the following contents.

<span class="highlight-inline"><pre><code>&lt;?php
namespace Spf13\SteveBundle\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;

/**
 * basic command class
 */
class yoCommand extends ContainerAwareCommand
{

    protected function configure()
    {
        $this
            -&gt;setName('yo')
            -&gt;setDescription('Tells you how great ___ is')
            -&gt;setDefinition(array(
                new InputArgument(
                    'label',
                    InputArgument::REQUIRED,
                    'The name you want to say hello to'
                ),
            ));
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $label = $input-&gt;getArgument('label');

        $output-&gt;writeln(sprintf('Hello %s', $label ));
    }

}
?&gt;
</code></pre>
</span>


Symfony2 will automatically locate and include the command as part of
the console commands.

Running your program
--------------------

    $ app/console yo steve

Hello steve

 

### Related Posts

-   [Next Gen PHP
    Frameworks](/post/next-gen-php-frameworks/)
-   [Creating your own Symfony2
    Bundle](/post/creating-your-own-symfony2-bundle/)
-   [On Symfony2](/post/symfony2/)
-   [Getting Started with
    Symfony2](/post/getting-started-with-symfony2/)

Other Resources
---------------

See
also [http://blog.liip.ch/archive/2010/12/21/using-the-symfony2-console.html](http://blog.liip.ch/archive/2010/12/21/using-the-symfony2-console.html)

