Skip to content

Instantly share code, notes, and snippets.

@boekkooi
Last active October 19, 2023 23:17
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save boekkooi/ff2ff146246d5ea20764 to your computer and use it in GitHub Desktop.
Save boekkooi/ff2ff146246d5ea20764 to your computer and use it in GitHub Desktop.
Doctrine keep alive (MySQL server has gone away)
<?php
namespace Acme\Doctrine\DBAL;
use Doctrine\DBAL\Connection;
declare(ticks = 3000000);
class ConnectionKeepAlive
{
/**
* @var Connection[]
*/
protected $connections;
protected $isAttached;
public function __construct()
{
$this->connections = array();
$this->isAttached = false;
}
public function detach()
{
unregister_tick_function(array($this, 'kick'));
$this->isAttached = false;
}
public function attach()
{
if ($this->isAttached || register_tick_function(array($this, 'kick'))) {
$this->isAttached = true;
return;
}
throw new \RuntimeException('Unable to attach keep alive to the system');
}
public function addConnection(Connection $logConnection)
{
$this->connections[spl_object_hash($logConnection)] = $logConnection;
}
public function kick()
{
foreach ($this->connections as $conn) {
try {
$conn->executeQuery('SELECT 1')->closeCursor();
} catch(\Exception $e) {
if ($conn === null || stripos($e->getMessage(), 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away') === false) {
throw $e;
}
$conn->close();
$conn->connect();
}
}
}
}
<?php
use Acme\Doctrine\DBAL\ConnectionKeepAlive;
$keepAlive = new ConnectionKeepAlive();
$keepAlive->addConnection($myConnection);
$keepAlive->attach();
// Do your very long running code
$keepAlive->detach();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment