Skip to content

@Bujhm /pattern singleton in PDO.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
paul dot maddox at gmail dot com 27-Aug-2009 12:54
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
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.