Symfony2中的Service DependencyInjection

时间:2012-03-22 13:06:52

标签: dependency-injection model symfony doctrine-orm kernel

我需要从控制器方法移动我的模型,所以我得到帮助将其更改为服务。服务本身可以工作,但我需要能够从这个服务内部连接到doctrine和kernel。起初我试图启用教义,但这造成了问题。我怎样才能做到这一点?我跟着文档并得到了这段代码。我不知道为什么我得到下面的错误。感谢您的帮助。

我的配置是:

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;
}

2 个答案:

答案 0 :(得分:1)

尝试注入@doctrine.orm.default_entity_manager

答案 1 :(得分:1)

在网络上我发现如何连接到Doctrine 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.

有什么想法吗?