PDO Singleton Class

the singleton design pattern allows you to have one and only one instance of a class/object. it is good for large, shared resources like databases. <?php /** @author Brian Danchilla @brief PDO singleton class */ class PDO_DBConnect { static $db ; private $dbh ; private function PDO_DBConnect () { $db_type = 'pgsql'; //ex) mysql, postgresql, oracle $db_name = 'myDatabase'; $user = 'brian' ; $password = 'myP@ssw0rd' ; $host = 'localhost' ; try { $dsn = "$db_type:host=$host;dbname=$db_name"; $this->dbh = new PDO ( $dsn, $user, $password); $this->dbh->setAttribute(PDO::ATTR_PERSISTENT, true); $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch ( PDOException $e ) { print "Error!: " . $e->getMessage () . "\n" ; die () ; } } public static function getInstance ( ) { if (! isset ( PDO_DBConnect::$db )) { PDO_DBConnect::$db = new PDO_DBConnect ( ) ; } return PDO_DBConnect::$db->dbh; } } ?>

sample usage would be $db_handle = PDO_DBConnect::getInstance(); ...

taxonomy: 

Add new comment