Created
August 25, 2013 22:21
-
-
Save mprz/6336658 to your computer and use it in GitHub Desktop.
Singleton Pattern for PDO MySQL
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
<?php | |
class DB{ | |
//variable to hold connection object. | |
protected static $db; | |
//private construct - class cannot be instatiated externally. | |
private function __construct() { | |
try { | |
// assign PDO object to db variable | |
self::$db = new PDO( 'mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS ); | |
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); | |
} | |
catch (PDOException $e) { | |
//Output error - would normally log this to error file rather than output to user. | |
echo "Connection Error: " . $e->getMessage(); | |
} | |
} | |
// get connection function. Static method - accessible without instantiation | |
public static function getConnection() { | |
//Guarantees single instance, if no connection object exists then create one. | |
if (!self::$db) { | |
//new connection object. | |
new db(); | |
} | |
//return connection. | |
return self::$db; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment