Created
April 5, 2011 00:15
-
-
Save Bujhm/902752 to your computer and use it in GitHub Desktop.
paul dot maddox at gmail dot com 27-Aug-2009 12:54
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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