public
Created

paul dot maddox at gmail dot com 27-Aug-2009 12:54

  • Download Gist
pattern singleton in PDO.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
 
I decided to create a singleton wrapper for PDO that ensures only one instance is ever used.
It uses PHP 5.3.0's __callStatic functionality to pass on statically called methods to PDO.
 
This means you can just call it statically from anywhere without having to initiate or define the object.
 
Usage examples:
 
<?php
DB::exec("DELETE FROM Blah");
 
foreach( DB::query("SELECT * FROM Blah") as $row){
print_r($row);
}
?>
 
Code:
 
<?php
 
class DB {
private static $objInstance;
/*
* Class Constructor - Create a new database connection if one doesn't exist
* Set to private so no-one can create a new instance via ' = new DB();'
*/
private function __construct() {}
/*
* Like the constructor, we make __clone private so nobody can clone the instance
*/
private function __clone() {}
/*
* Returns DB instance or create initial connection
* @param
* @return $objInstance;
*/
public static function getInstance( ) {
if(!self::$objInstance){
self::$objInstance = new PDO(DB_DSN, DB_USER, DB_PASS);
self::$objInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$objInstance;
} # end method
/*
* Passes on any static calls to this class onto the singleton PDO instance
* @param $chrMethod, $arrArguments
* @return $mix
*/
final public static function __callStatic( $chrMethod, $arrArguments ) {
$objInstance = self::getInstance();
return call_user_func_array(array($objInstance, $chrMethod), $arrArguments);
} # end method
}
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.