Forked from extraordinaire/reconnecting_pdo.php
Last active
December 1, 2022 13:26
-
-
Save zhengwy888/62f0442f9158935568d1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
class ReconnectingPDO | |
{ | |
protected $dsn, $username, $password, $pdo, $driver_options; | |
public function __construct($dsn, $username = "", $password = "", $driver_options = array()) | |
{ | |
$this->dsn = $dsn; | |
$this->username = $username; | |
$this->password = $password; | |
$this->driver_options = $driver_options; | |
} | |
public function __call($name, array $arguments) | |
{ | |
try { | |
//$this->connection()->query("SHOW STATUS;")->execute(); | |
// this enables lastInsertID(), but I don't know if it will break other stuff | |
return call_user_func_array(array($this->connection(), $name), $arguments); | |
} catch(\PDOException $e) { | |
if($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) { | |
throw $e; | |
} | |
$this->reconnect(); | |
return call_user_func_array(array($this->connection(), $name), $arguments); | |
} | |
} | |
protected function connection() | |
{ | |
return $this->pdo instanceof \PDO ? $this->pdo : $this->connect(); | |
} | |
public function connect() | |
{ | |
$this->pdo = new PDO($this->dsn, $this->username, $this->password, (array) $this->driver_options); | |
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
return $this->pdo; | |
} | |
public function reconnect() | |
{ | |
$this->pdo = null; | |
return $this->connect(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment