Skip to content

Instantly share code, notes, and snippets.

@mprz
Created August 25, 2013 22:21
Show Gist options
  • Save mprz/6336658 to your computer and use it in GitHub Desktop.
Save mprz/6336658 to your computer and use it in GitHub Desktop.
Singleton Pattern for PDO MySQL
<?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