symfony2:控制器中的服务访问引发异常 - “错误:在非对象上调用成员函数get()”

时间:2014-07-03 18:33:03

标签: php symfony service dependency-injection

我在src\trollmaster\TrollBundle\Services\DefaultService.php

中提供了服务
namespace trollmaster\TrollBundle\DefaultService;

class DefaultService
{
    protected $example;

    protected function exampleFunction()
    {
        return null;
    }
}

我的资源\ config \ services.yml:

services:
    trollmaster.default_service:
        class: trollmaster\TrollBundle\DefaultService

和命令php app/console container:debug正确地返回了我的服务名称,但是当我想在Controller的构造中调用此服务时:

$this->DefaultService = $this->get("trollmaster.default_service");

我看到了这个错误:

Error: Call to a member function get() on a non-object

我做错了什么?


编辑:

当我想将控制器定义为服务

/**
 * @Route(service="DefaultController")
 */
class DefaultController

我收到了错误:

ClassNotFoundException: Attempted to load class "DefaultController" from namespace "trollmaster\TrollBundle

2 个答案:

答案 0 :(得分:2)

原因是容器被注入到实现ContainerAwareInterface

的控制器中

...(即通过扩展Symfony\Bundle\FrameworkBundle\Controller\Controller)......

...通过 setter-injection


TLDR:在构建对象之后执行setter-injection。

因此你无法做到......

$service = $this->get('service');
// ... or ...
$service = $this->container->('service');

...在__construct()方法中,因为setContainer()方法未被调用且$this->container尚未设置。

您可以在 documentation 中详细了解不同类型的注射剂。


查看以下代码部分:

  • Controller延伸ContainerAware here

  • ContainerAware提供setContainer()方法 here

答案 1 :(得分:1)

这是因为构造函数不知道容器(如nifr解释的那样)。但你可以define your controller itself as a service。这是我猜的最好的做法,虽然我不知道你想要做什么。