1

I want to run a task using console. I checked http://symfony.com/doc/2.0/components/console/introduction.html

It asks to create GreetCommand.php.

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()
    {
        $this
            ->setName('demo:greet')
            ->setDescription('Greet someone')
            ->addArgument(
                'name',
                InputArgument::OPTIONAL,
                'Who do you want to greet?'
            )
            ->addOption(
               'yell',
               null,
               InputOption::VALUE_NONE,
               '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);
        }

        $output->writeln($text);
    }
}

and create another file to run the command as given below.

#!/usr/bin/env php
# app/console
<?php

use Acme\DemoBundle\Command\GreetCommand;
use Symfony\Component\Console\Application;

$application = new Application();
$application->add(new GreetCommand);
$application->run();

But the command to run it is like app/console demo:greet Fool

The thing I won't understand is that why we need to create the second file?

Sometimes, I feel Symfony is the most difficult framework to learn.

1
  • I suppose that is designed in that way to separate definition of functions, tasks and so on, from the way you recall it. Commented Mar 4, 2013 at 8:01

1 Answer 1

2

In first file you have defined your Command class.

Second file is needed to register/initialize instance of that command. You just tell there that your application will have GreetCommand with name "demo:greet" (name defined in command itself).

BTW When you use full-stack Symfony2 with FrameworkBundle you do not have to create second file (if we follow Symfony2 conventions) cause Command is registered automatically by FrameworkBundle Console Application using HttpKernel component

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.