Mohammed H
Mohammed H

Reputation: 7048

The Console Component in Symfony

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.

Upvotes: 1

Views: 353

Answers (1)

l3l0
l3l0

Reputation: 3393

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

Upvotes: 2

Related Questions