在某些情况下无法将EntityManager注入构造函数

时间:2014-04-27 19:33:17

标签: php symfony dependency-injection

我遇到了一些奇怪的情况。我已经定义了一个服务,并将它作为Controller构造函数的参数赋予它EntityManager。当我试图在其他构造函数中获取我的服务(它是构造函数)时,一切正常。但是当我直接打开构造函数时,我看到了这个服务:

ContextErrorException: Catchable Fatal Error: Argument 1 passed to 
Webrama\PbsTreeBundle\Controller\PbsTreeController::__construct() must be an instance 
of Doctrine\ORM\EntityManager, none given, called in 
C:\www\strefaurody\bb\app\cache\dev\classes.php on line 2374 and defined in 
C:\www\strefaurody\bb\src\Webrama\PbsTreeBundle\Controller\PbsTreeController.php
 line 16

我的services.yml看起来像这样:

services:
    pbs_tree_controller:
        class: Webrama\PbsTreeBundle\Controller\PbsTreeController
        arguments:
            entityManager: "@doctrine.orm.entity_manager

构造函数也很简单:

private $em;

        public function __construct(EntityManager $entityManager)
        {
            $this->em = $entityManager;
        }

奇怪的是,我正在使用注入构造函数EntityManager实例的服务调用方法并成功:

public function genratePbsTree()
        {

            $conn = $this->em->getConnection();

            $sql = "SELECT id_child AS id, TRIM(TRAILING '/' FROM path) AS path FROM pbs_node_to_node WHERE depth = 2";
            $stmt = $conn->prepare($sql);
            $stmt->execute();
            $result = $stmt->fetchAll();

            return $result;
        }

根据要求提供路由YML:

webrama_pbs_index:
    pattern:  /{page}
    defaults: { _controller: WebramaPbsTreeBundle:PbsTree:index, page: 1 }
    requirements:
      page:  \d+

webrama_pbs_brand_edit:
    pattern: /edit/{id}
    defaults: { _controller: WebramaPbsTreeBundle:PbsTree:edit, id: '' }
    requirements:
      id:  \d+
    options:
          expose: true

webrama_pbs_producer_add:
    pattern: /add/producer
    defaults: { _controller: WebramaPbsTreeBundle:PbsTree:addProducer }

webrama_pbs_series_add:
    pattern: /add/series
    defaults: { _controller: WebramaPbsTreeBundle:PbsTree:addSeries }

webrama_pbs_brand_add:
    pattern: /add/brand
    defaults: { _controller: WebramaPbsTreeBundle:PbsTree:addBrand }

1 个答案:

答案 0 :(得分:0)

您在路由配置中使用“控制器”表示法:

_controller: WebramaPbsTreeBundle:PbsTree:index

如果您想要“控制器作为服务”,您需要使用服务名称:

_controller: pbs_tree_controller:indexAction

在此处阅读更多内容:http://symfony.com/doc/current/cookbook/controller/service.html