问题
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?
回答1:
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 ]
回答2:
You can reach the connection from $_em attribute of EntityRepository class so here is how you could do it;
$connection = $this->_em->getConnection();
回答3:
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.
回答4:
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;
}
}
来源:https://stackoverflow.com/questions/14641918/having-a-custom-repository-with-dbal-connection-in-symfony-2-doctrine-2