Sjaak Trekhaak
Sjaak Trekhaak

Reputation: 4966

Get a Service Definition in a Symfony2 ContainerAwareCommand

I'm trying to get a Service Definition in a ContainerAwareCommand as per http://symfony.com/doc/2.0/components/dependency_injection/definitions.html#getting-and-setting-service-definitions

However, this immediately results in a failure:

Fatal error: Call to undefined method appDevDebugProjectContainer::getDefinition()

I couldn't find much more in the docs about this behaviour, any ideas?

EDIT: Code example:

class MyCommand extends ContainerAwareCommand {

    protected function execute(InputInterface $p_vInput, OutputInterface $p_vOutput) {
        try {
            var_dump($this->getContainer()->getDefinition('api.driver'));
        } catch (\Exception $e) {
            print_r($e);
            exit;
        }
    }

}

Upvotes: 2

Views: 2030

Answers (1)

Cyprian
Cyprian

Reputation: 11364

In example that you provided $container is not instance of Container class, but ContainerBuilder class. Container has not any method named getDefinition().

I can't say much more if you don't show context where you want use that definition.

edit:

Below I've posted example of code using ContainerBuilder. It's copied directly from symfony's command, so I guess it's good example of use.

// Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php

/**
 * Loads the ContainerBuilder from the cache.
 *
 * @return ContainerBuilder
 */
private function getContainerBuilder()
{
    if (!$this->getApplication()->getKernel()->isDebug()) {
        throw new \LogicException(sprintf('Debug information about the container is only available in debug mode.'));
    }

    if (!file_exists($cachedFile = $this->getContainer()->getParameter('debug.container.dump'))) {
        throw new \LogicException(sprintf('Debug information about the container could not be found. Please clear the cache and try again.'));
    }

    $container = new ContainerBuilder();

    $loader = new XmlFileLoader($container, new FileLocator());
    $loader->load($cachedFile);

    return $container;
}

Best!

Upvotes: 3

Related Questions