goat goat - 1 year ago 83
MySQL Question

Reusing the database connection used by the doctrine entity manager

Doctrine encapsulates the native, driver specific database connection resource handle inside of its Connection classes. I'm talking about the resource returned from, for example,

. I don't see any way to access the raw connection resource - there's no getter methods that I've been able to find. This strong encapsulation should probably be a hint that I shouldn't try to access it, and use it, but of course, that's exactly what I want to do.

Would it cause any problem if I were to issue read-only select queries from the same connection? I'm not sure how doctrine's work flow operates under the hood. Database connections are stateful, and I'm a bit scared that I might jump in and issue an sql query at a moment when doctrine has some multi-step transaction partially in progress, and that would obviously cause a problem. But with php's single threaded nature I think there's a decent chance it might not be possible in practice, depending on how doctrine works.

Aside: The reason I want to do this is for performance. I have some other code that isn't written with doctrine, and it wants a raw database connection because it uses the native db extension functions. I could just open another db connection, but opening a second connection has significant performance implications in my scenario...making it very appealing to try to reuse the doctrines connection.

Answer Source

Try getWrappedConnection it returns instance of Doctrine\DBAL\Driver\PDOConnection which is a wrapper for \PDO:

$connection = $this->getEntityManager()

$stmt = $connection->prepare('SELECT * FROM `City`');

P.S. I believe it is perfectly normal to reuse an existing connection, instead of creating a new one. I am doing this in a project that has Doctrine1 and Doctrine2.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download