2012-03-22 41 views
6

我需要我的模型从控制器的方法移动,所以我得到的帮助将其更改为一个服务。该服务本身起作用,但我需要能够从此服务内部连接到教条和内核。起初我试图启用教义,但是这造成了问题。我该如何做这项工作?我遵循文档并获得了此代码。我不知道为什么我得到下面的错误。提前谢谢你的帮助。服务DependencyInjection在Symfony2中

我的配置是:

CSVImport.php

namespace Tools\TFIBundle\Model; 

use Doctrine\ORM\EntityManager; 

class CSVImport { 
    protected $em; 

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

应用/配置/ config.yml

services: 
    csvimport: 
     class: Tools\TFIBundle\Model\CSVImport 
     arguments: [ @doctrine.orm.entity_manager ] 

在控制器动作

$cvsimport = $this->get('csvimport'); 

我的错误

Catchable Fatal Error: Argument 1 passed to 
Tools\TFIBundle\Model\CSVImport::__construct() must be an instance of 
Doctrine\ORM\EntityManager, none given, called in 
.../Tools/TFIBundle/Controller/DefaultController.php on line 58 and defined in 
.../Tools/TFIBundle/Model/CSVImport.php line 12 

编辑,我的工作代码:

服务类代码与内核连接到它

namespace Tools\TFIBundle\Model; 

use Doctrine\ORM\EntityManager, 
    AppKernel; 

class CSVImport { 
    protected $em; 
    protected $kernel; 
    protected $cacheDir; 

    public function __construct(EntityManager $em, AppKernel $k) { 
     $this->em = $em; 
     $this->kernel = $k; 
} 

回答

1

尝试注射@doctrine.orm.default_entity_manager

+0

此提示帮我找到真正的问题,配置是确定的,但我在控制器代码打错的电话得这使得这些错误的服务。 – nysander 2012-03-22 17:13:33

+0

同样的事情用于获取DBAL连接。有人可以解释它背后的逻辑吗? – Robert 2017-12-05 21:23:46

1

在网上我发现了如何连接到学说DBAL才能够让我自己查询。但是,当我改变了我的配置这一项:

应用程序/ config.yml

services: 
    csvimport: 
     class: Tools\TFIBundle\Model\CSVImport 
     arguments: [ @doctrine.dbal.connection, @doctrine.orm.entity_manager, @kernel ] 

类定义

namespace Tools\TFIBundle\Model; 

use Doctrine\ORM\EntityManager, 
    Doctrine\DBAL\Connection, 
    AppKernel; 

class CSVImport { 
    protected $c; 
    protected $em; 
    protected $kernel; 

    public function __construct(Connection $c, EntityManager $em, AppKernel $k) { 
     $this->c = $c; 
     $this->em = $em; 
     $this->kernel = $k; 
    } 

我得到错误:

RuntimeException: The definition "csvimport" has a reference to an abstract definition "doctrine.dbal.connection". Abstract definitions cannot be the target of references. 

有任何想法吗?