作为服务的Symfony2 FOSRest控制器有一个空容器

时间:2015-06-12 08:04:40

标签: symfony dependency-injection

我已将我的控制器注册为服务,因此我可以将我的存储库注入我的控制器。这一切似乎工作正常,但现在当我尝试返回视图时,它会返回数据。

它出错并尝试加载fos_rest.view_handler

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

$this->container->get($id)上的symfony2控制器类中调用get。出于某种原因,当我将控制器用作服务时,ContainerInterface不再被注入ContainerAware

之前有没有人遇到过这个问题?如何确保注入相同的容器?

这就是我将我的班级宣布为服务的方式:

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="acme.users.apibundle.controller.user_controller" class="Acme\Users\ApiBundle\Controller\UserController">
            <argument type="service" id="acme.users.user_repository"/>
        </service>
    </services>
</container>

这是我的控制者:

class UserController extends FOSRestController
{
    private $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function indexAction()
    {

        $users = $this->repository->findAll();

        $view = $this->view($users, 200)
                 ->setTemplate("MyBundle:Users:getUsers.html.twig")
                 ->setTemplateVar('users');

        return $this->handleView($view);
    }
}

1 个答案:

答案 0 :(得分:3)

您需要使用call将容器注入控制器,以便handleView方法可以使用它。

将配置更改为..

<container xmlns="http://symfony.com/schema/dic/services"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
    <service id="acme.users.apibundle.controller.user_controller" class="Acme\Users\ApiBundle\Controller\UserController">
        <argument type="service" id="acme.users.user_repository"/>
        <!-- inject the container via the setContainer method -->
        <call method="setContainer">
            <argument type="service" id="service_container" />
        </call>
    </service>
</services>