【问题标题】:Get a Service Definition in a Symfony2 ContainerAwareCommand在 Symfony2 ContainerAwareCommand 中获取服务定义
【发布时间】:2012-10-17 10:46:10
【问题描述】:

我正在尝试根据 http://symfony.com/doc/2.0/components/dependency_injection/definitions.html#getting-and-setting-service-definitions 在 ContainerAwareCommand 中获取服务定义

但是,这会立即导致失败:

致命错误:调用未定义的方法 appDevDebugProjectContainer::getDefinition()

我在文档中找不到更多关于这种行为的信息,有什么想法吗?

编辑:代码示例:

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

}

【问题讨论】:

  • 拜托,你能提供你写的那一堆代码吗?

标签: php symfony dependency-injection


【解决方案1】:

在您提供的示例中,$container 不是Container 类的实例,而是ContainerBuilder 类。容器没有任何名为getDefinition() 的方法。

如果你不显示你想要使用该定义的上下文,我不能说更多。

编辑:

下面我发布了使用ContainerBuilder 的代码示例。它是直接从 symfony 的命令中复制而来的,所以我想这是一个很好的使用示例。

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

最好的!

【讨论】:

  • 很好的答案,按预期工作。你能详细说明为什么这会返回与 ContainerAwareCommand->getContainer() 不同的东西吗?
  • 我不确定您是否理解上面的问题,但 Container 类与 ContainerBuilder 类不同。 ContainerAwareCommand->getContainer() 返回类 Container 的对象。您需要 ContainerBuilder,因此您必须像我的回答那样行事。
  • 好吧,我的印象是容器也有能力获得定义!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 2014-12-02
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多