Robbo_UK
Robbo_UK

Reputation: 12149

symfony2 custom console how do I include the container?

How do I fetch the container inside a custom console command script?

im hoping to be able to call

$this->container->get('kernel')->getCachedir();

or

$this->getDoctrine();

I can call the above two examples inside the controller but not in the command?.. see simplified example below

namespace Portal\WeeklyConversionBundle\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 ExampleCommand extends ContainerAwareCommand
{

    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';
        }

        // this returns an error?
        // $cacheDir = $this->container->get('kernel')->getCachedir();

        // edit - this works
        $this->getContainer()->get('kernel')->getCacheDir();


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

returns an undefined error message?.. How do I define it? I thought that by adding ContainerAwareCommand that I would have access to this->container?

Upvotes: 0

Views: 790

Answers (1)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

What about using,

$this->getContainer()->get('kernel')->getCacheDir();

Take a look at the Getting Services from the Service Container section on How to create a Console Command part of the documention.

From the documentation,

By using ContainerAwareCommand as the base class for the command (instead of the more basic Command), you have access to the service container. In other words, you have access to any configured service.

Upvotes: 2

Related Questions