2012-03-22 72 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. 

有任何想法嗎?