Paweł Madej
Paweł Madej

Reputation: 1279

Service DependencyInjection in Symfony2

I needed to move my model from the controller method, so I got help to change it to a service. The service by itself works, but I need to be able to connect to doctrine and the kernel from inside of this service. At first I tried to enable doctrine, but that created problems. How can I make this work? I've followed docs and got this code. I have no idea why I got the error below. Thank you for your help in advance.

My config is:

CSVImport.php

namespace Tools\TFIBundle\Model;

use Doctrine\ORM\EntityManager;

class CSVImport  {
    protected $em;

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

app/config/config.yml

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

action in controller

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

MY ERROR

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

EDIT, my working code:

service class code with Kernel attached to it

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

Upvotes: 6

Views: 4015

Answers (2)

Paweł Madej
Paweł Madej

Reputation: 1279

On web I've found how to connect to Doctrine DBAL to be able to make queries on my own. But when i changed my configuration to this one:

app/config.yml

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

class definition

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

i got error:

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

Any ideas?

Upvotes: 0

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

Try injecting @doctrine.orm.default_entity_manager.

Upvotes: 1

Related Questions