Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Service Container in Symfony 2 Console Command gives "getKernel() on a non-object"

In the configure() function, I tried to get the service container

class SetQuotaCommand extends ContainerAwareCommand {

    protected function configure() {
        parent::configure();
        die(get_class($this->getContainer()));

PHP Fatal error: Call to a member function getKernel() on a non-object in ...\Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.php on line 37

Do I need to do something different?

UPDATE

I noticed that it works if I call getContainer in execute(). But I wonder if its possible to getContainer() in configure(). I want to get a configuration parameter for use in addOption default value argument.

Otherwise I could use

$param1 = $input->getOption('param1') ? : $container->getParameter('param1'); 

Which appears abit more un-intuitive?

like image 763
Jiew Meng Avatar asked Jan 05 '12 07:01

Jiew Meng


3 Answers

Call $this->container = $this->getApplication()->getKernel()->getContainer(); in execute(). See https://stackoverflow.com/a/7517803/297679

like image 57
Nobu Avatar answered Nov 20 '22 07:11

Nobu


It appears service container has not been initialized in configure. I can access it in execute.

As for defaults for console options, I can use something like

$opt1 = $input->getOption('opt1') ? : $default;

In many cases Symfony2 allows you to set a default value when retrieving parameters/variables. So a shortcut for the above mentioned solution would simply be:

$opt1 = $input->getOption('opt1', $default);

Just putting this as an answer so I can close this if theres no other answers.

like image 2
Jiew Meng Avatar answered Nov 20 '22 07:11

Jiew Meng


Despite all the information I found on Google (including this thread) nothing seems to worked. I finally figured out why I wasn't able to get a kernel.

In a 1:1 copy from the docs, i created a file application.php:

#!/usr/bin/env php
<?php
// application.php

require __DIR__.'/vendor/autoload.php';
require __DIR__.'/app/AppKernel.php';

use X\SnmpBundle\Command\GreetCommand;
use Symfony\Component\Console\Application;

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

And then execute the application by running:

./application.php this:that or php application.php this:that

This didn't work for me. For some reason the kernel is not available when doing this. However, it is when I run the application using:

php app/console this:that

My guess is that running app app/console does a lot more then my application.php does, such as starting a kernel.

With running the app as "php app/console this:that" everything works fine and I am able to use:

$this->getContainer()->get('doctrine')->getManager();

which was what I needed.

like image 2
Rudy Broersma Avatar answered Nov 20 '22 06:11

Rudy Broersma