6

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;
}
Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
Paweł Madej
  • 1,229
  • 23
  • 42

2 Answers2

1

Try injecting @doctrine.orm.default_entity_manager.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • this hint helped me to find real problem, configuration was ok, but I got in controller code wrong call to that service which made those errors. – Paweł Madej Mar 22 '12 at 17:13
  • The same thing worked for obtaining DBAL connection. Can someone explain what's the logic behind it? – Robert Dec 05 '17 at 21:23
0

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?

Paweł Madej
  • 1,229
  • 23
  • 42