Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 custom console command not working

Tags:

symfony

I created a new Class in src/MaintenanceBundle/Command, named it GreetCommand.php and put the following code in it:

<?php

namespace SK2\MaintenanceBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
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 ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('maintenance: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 tried to call it via

app/console maintenance:greet Fabien

But i always get the following error:

[InvalidArgumentException] There are no commands defined in the "maintenance" namespace.

Any ideas?

like image 447
prehfeldt Avatar asked Sep 13 '11 16:09

prehfeldt


2 Answers

I had this problem, and it was because the name of my PHP class and file didn't end with Command.

Symfony will automatically register commands which end with Command and are in the Command directory of a bundle. If you'd like to manually register your command, this cookbook entry may help: http://symfony.com/doc/current/cookbook/console/commands_as_services.html

like image 58
Sam Avatar answered Oct 10 '22 12:10

Sam


I had a similar problem and figured out another possible solution:

If you override the default __construct method the Command will not be auto-registered by Symfony, so you have to either take the service approach as mentioned earlier or remove the __construct override and make that init step in the execute method or in the configure method.

Does actually anyone know a good best practice how to do init "stuff" in Symfony commands?

It took me a moment to figure this out.

like image 40
MonocroM Avatar answered Oct 10 '22 10:10

MonocroM