1

I'm trying to inject default DBAL connection into a custom repository associated with a entity so I can do some raw sql query.

In services.mxl

<service id="acme.repository.document" class="Acme\Bundle\Repository\DocumentRepository">
      <argument type="service" id="doctrine.orm.entity_manager" />
      <argument>Acme\Bundle\Entity\Document</argument>
      <argument type="service" id="database_connection" />
</service>

In my repository class DocumentRepository.php

class DocumentRepository extends EntityRepository {

    protected $conn;

    public function __construct($em, $class, Connection $conn)
    {
        $this->conn = $conn;
         parent::__construct($em,$class);
    }

But I get this error:

Catchable Fatal Error: Argument 3 passed to Acme\Bundle\Repository\DocumentRepository::__construct() must be an instance of Doctrine\DBAL\Connection, none given, called in /project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php on line 689 and defined in /project/src/Acme/Bundle/Repository/DocumentRepository.php line 18

May you help me?

j0k
  • 22,600
  • 28
  • 79
  • 90
Vittore
  • 240
  • 3
  • 15

4 Answers4

4

After a lot of hours continue search for the optimal answer. I found the answer of Elnur Abdurrakhimov is the best one (in my opinion, and my use cases).

Source: https://stackoverflow.com/a/12908748/1617890

use Doctrine\DBAL\Connection;

public function __construct(Connection $connection)
{
    $this->connection = $connection;
}
my_listener:
    arguments: [ @database_connection ]
Community
  • 1
  • 1
redstrike
  • 124
  • 1
  • 3
  • 8
2

You can reach the connection from $_em attribute of EntityRepository class so here is how you could do it;

$connection = $this->_em->getConnection();
ag0702
  • 381
  • 1
  • 6
  • 18
0

EntityRepository in Doctrine ORM is built internally. You can still define your own service, which can be a repository too, and then use that one. That's a limitation of the ORM since Doctrine does not use service location or dependency injection containers internally.

Ocramius
  • 25,171
  • 7
  • 103
  • 107
-1

the problem is that you aren't passing the correct instance of Connection, try this:

use Doctrine\DBAL\DriverManager;

class DocumentRepository extends EntityRepository 
{

    protected $conn;

    public function __construct($em, $class)
    {
        $this->conn = $this->myHandleConnection();
         parent::__construct($em,$class);
    }

    public function myHandleConnection()
    {
        $config = new \Doctrine\DBAL\Configuration();
        $connectionParams = array(
                'dbname' => 'MY_DB',
                'user' => 'root',
                'password' => 'root',
                'host' => 'localhost',
                'driver' => 'pdo_mysql',
                'charset' => 'utf8',
                );
        $conn = DriverManager::getConnection($connectionParams, $config);
        return $conn;
    }
}
linuxatico
  • 1,878
  • 30
  • 43