Search This Blog

Thursday, February 21, 2013

Symfony 2 Command Line

Symfony 2 Command Line

This well documented in Git/Packagist and also here in in the Symfony 2 documentation.
This post will go into more detail re running classes from the command line, but first a bit more information, re the example class that extends the Command class:

namespace Acme\DemoBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GreetCommand extends Command
    protected function configure()
            ->setDescription('Greet someone')
                'Who do you want to greet?'
               'If set, the task will yell in uppercase letters'

    protected function execute(InputInterface $input, OutputInterface $output)
        $name = $input->getArgument('name');
        if ($name) {
            $text = 'Hello '.$name;
        } else {
            $text = 'Hello';

        if ($input->getOption('yell')) {
            $text = strtoupper($text);


The parts in bold - specifically:

  • The end of the class name GreetCommand,
  • The parent folder - Command (and last item in the namespace path)
Must both be Command for the classes to be recognised by the app/console script without any further configuration.
Also the string parameter in the setName call should be checked and if necessary edited.
I was able to get custom commands working in Symfony 2.1 by:
  1. Installing the component using Composer.
  2. Creating the above php file - editing the value above as needed.
$ app/console --list
Symfony version 2.1.8-DEV - app/dev/debug
  test:greet                            Greet someone
  test:update                           Update someone


No comments:

Post a Comment