Skip to content

Instantly share code, notes, and snippets.

@ozh
Created February 4, 2014 21:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ozh/8812721 to your computer and use it in GitHub Desktop.
Save ozh/8812721 to your computer and use it in GitHub Desktop.
Adding ping() function to PDO
<?php
// http://terenceyim.wordpress.com/2009/01/09/adding-ping-function-to-pdo/
class NPDO {
private $pdo;
private $params;
public function __construct() {
$this->params = func_get_args();
$this->init();
}
public function __call($name, array $args) {
return call_user_func_array(array($this->pdo, $name), $args);
}
// The ping() will try to reconnect once if connection lost.
public function ping() {
try {
$this->pdo->query('SELECT 1');
} catch (PDOException $e) {
$this->init(); // Don't catch exception here, so that re-connect fail will throw exception
}
return true;
}
private function init() {
$class = new ReflectionClass('PDO');
$this->pdo = $class->newInstanceArgs($this->params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment