将Doctrine Repository注入控制器

时间:2015-09-18 13:34:15

标签: symfony service dependency-injection controller repository

我有以下控制器:

<?php

namespace AppBundle\Controller;

use AppBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;

class UserController extends BaseController 
{
    public function allAction(Request $request)
    {
        $users = $this->getDoctrine()
                      ->getRepository('AppBundle:User')
                      ->findAll();

        return $this->respond(['users' => $users], 200);
    } 
}

我想将存储库注入控制器(用于测试目的)

控制器:

<?php

namespace AppBundle\Controller;

use AppBundle\Controller\BaseController;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;

class UserController extends BaseController 
{
    private $userrepository;

    public function __construct(EntityRepository $userrepository)
    {
        $this->userrepository = $userrepository;
    }

    public function allAction(Request $request)
    {
        $users = $this->userrepository->findAll();
        return $this->respond(['users' => $users], 200);
    } 
}

services.yml

services:

    userrepository:
        class: Doctrine\ORM\EntityRepository
        factory_service: doctrine.orm.entity_manager
        factory_method: getRepository
        arguments:
            - AppBundle\Entity\User

    usercontroller:
        class: AppBundle\Controller\UserController
        arguments:
            - "@userrepository"

的routing.yml

api_users_all:
    path: /api/users.{_format}
    defaults: { _controller: usercontroller:allAction, _format: json }
    requirements:
        _method: GET

我一直面临以下错误:

PHP致命错误:在/ Applications / MAMP / htdocs / api / vendor / symfony / symfony / src / Symfony / Bundle / FrameworkBundle / Controller / Controller中的非对象上调用成员函数get()第350行的.php

第350行

return $this->container->get($id);

所以我的猜测是控制器不再是“ContainerAware&#39;或类似的东西。

但我似乎无法解决这个问题。

我正在使用symfony 2.7

1 个答案:

答案 0 :(得分:4)

将路由器配置为通过服务调用控制器后,控制器不会直接创建,而是从“依赖注入”容器中请求。是的,不再有容器,因为你只注入一个参数:user repository。

如果您想要整个容器(不推荐使用),并且您在BaseController中扩展了Symfony Controller,请将其设置为您的服务:

services:
    usercontroller:
        class: AppBundle\Controller\UserController
        calls: 
            - [setContainer, ["@service_container"]]
        arguments:
            - "@userrepository"

如果您不扩展Symfony Controller,请将容器注入参数:

services:
    usercontroller:
        class: AppBundle\Controller\UserController
        arguments:
            - "@userrepository"
            - "@service_container"

控制器:

class UserController extends BaseController 
{
private $userrepository;
private $container;

public function __construct(EntityRepository $userrepository, $container)
{
    $this->userrepository = $userrepository;
    $this->container = $container;
}

不推荐,只注射你想要的东西,例如。如果你在你的控制器中使用只有存储库和邮件程序只注入它们而不是整个容器。