class DB
{
protected static $pdo = null;
public static function getConnection() {
// initialize $pdo on first call
if (self::$pdo == null) {
self::init();
}
// now we should have a $pdo, whether it was initialized on this call or a previous one
// but it could have experienced a disconnection
try {
echo "Testing connection...\n";
$old_errlevel = error_reporting(0);
self::$pdo->query("SELECT 1");
} catch (PDOException $e) {
echo "Connection failed, reinitializing...\n";
self::init();
}
error_reporting($old_errlevel);
return self::$pdo;
}
protected static function init() {
try {
echo "Opening new connection...\n";
self::$pdo = new PDO('mysql:host=huey;dbname=test', 'root', 'root',array(PDO::ATTR_PERSISTENT => true));
self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e->getMessage());
}
}
}