Refresh the database connection if connection drops or times out

I guess you mean to connect to the database if the connection is lost for some reason. Given an EntityManager, you can do it the following way:

$success = $_em->getConnection()->connect();

With getConnection, you are retrieving the connection object doctrine uses (Doctrine\DBAL\Connection), which exposes the connect method.

You can call connect anytime, as it checks wether a connection is already established. If this is the case, it returns false.

There is also a isConnected method to check wether a connection is established. You could use that to see where exactly the connection is dropping to get a clearer picture of what is happening.


A different approach is to check if Doctrine is still connected to the MySQL server through the ping() method in the connection. If the connection is lost, close the active connection since it is not really closed yet and start a new one.

if(FALSE == $em->getConnection()->ping()){
    $em->getConnection()->close();
    $em->getConnection()->connect();
}