note 93178 added to book.pdo
| From: | paul dot maddox at gmail dot com | Date: | Thu, 27 Aug 2009 12:54:14 +0000 |
| Subject: | note 93178 added to book.pdo | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-159921@lists.php.net to get a copy of this message | ||
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:
DB::exec("DELETE FROM Blah");
foreach( DB::query("SELECT * FROM Blah") as $row){
print_r($row);
}
<?
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
}
?>
----
Server IP: 87.124.86.41
Probable Submitter: 87.86.105.3 (proxied: 87.86.105.3)
----
Manual Page -- http://www.php.net/manual/en/book.pdo.php
Edit -- https://master.php.net/note/edit/93178
Del: integrated -- https://master.php.net/note/delete/93178/integrated
Del: useless -- https://master.php.net/note/delete/93178/useless
Del: bad code -- https://master.php.net/note/delete/93178/bad+code
Del: spam -- https://master.php.net/note/delete/93178/spam
Del: non-english -- https://master.php.net/note/delete/93178/non-english
Del: in docs -- https://master.php.net/note/delete/93178/in+docs
Del: other reasons-- https://master.php.net/note/delete/93178
Reject -- https://master.php.net/note/reject/93178
Search -- https://master.php.net/manage/user-notes.php