Last active
October 19, 2023 23:17
-
-
Save boekkooi/ff2ff146246d5ea20764 to your computer and use it in GitHub Desktop.
Doctrine keep alive (MySQL server has gone away)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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