ZF2 + Doctrine2: Server has gone away - how to jog

2019-02-20 00:31发布

问题:

Thanks in advance for your help.

I'm wondering if anyone quickly knows what functions to call on the Entity Repository to jog its reconnection if it is dead. I am running some jobs that can take a length of time that exceeds wait_timeout through a ZF2 CLI route, and unfortunately, the ER's connection dies by the time it needs to get used (when the job is done).

Need:

// do the long job

$sl = $this->getServiceLocator();
$mapper = $sl->get( 'doctrine_object_mapper' );
if( !$mapper->getRepository()->isAlive() ) // something like so
    $mapper->getRepository()->wakeTheHellUp();

Aren't those proper method names! ;)

Thanks again.

回答1:

This is a fairly common problem with long running processes and connections.

The solution is to retrieve the ORM's DBAL connection and re-create it if the connection was lost (ensuring it didn't die during a transaction). This is obviously annoying, but it's the only way of doing it right now:

// note - you need a ServiceManager here, not just a generic service locator
$entityMAnager = $serviceManager->get('entity_manager');
$connection    = $entityManager->getConnection();

try {
    // dummy query
    $connection->query('SELECT 1');
} catch (\Doctrine\DBAL\DBALException $e) {
    if ($connection->getTransactionIsolation()) {
        // failed in the middle of a transaction - this is serious!
        throw $e;
    }

    // force instantiation of a new entity manager
    $entityManager = $serviceManager->create('entity_manager');
}

$this->doFoo($entityManager);