Warm tip: This article is reproduced from serverfault.com, please click

Symfony2 custom console command not working

发布于 2011-09-13 16:13:51

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?

Questioner
prehfeldt
Viewed
0
447 2016-12-14 18:56:02

I figured out why it was not working: I simply forgot to register the Bundle in the AppKernel.php. However, the other proposed answers are relevant and might be helpful to resolve other situations!

By convention: the commands files need to reside in a bundle's command directory and have a name ending with Command.

in AppKernel.php

public function registerBundles()
{
    $bundles = [
        ...
        new MaintenanceBundle\MaintenanceBundle(),
    ];

    return $bundles;
}