Single Database Object in PHP 5 Using the Singleton Pattern
Posted on Sep 14, 2009 @ 1:06 PM
Found this over on www.ultramegatech.com/, it's an easy way to share one instance of a database connection. I've made a couple of changes to the code.
<?php
/*
Calling the call() method statically will give you access to the MySQLi methods.
Whenever you need to make a query, you just have to do this:
$result = Database::call()->query("SELECT * FROM ...");
*/
class Database
{
const MYSQL_HOST = "";
const MYSQL_USER = "";
const MYSQL_PASS = "";
const MYSQL_DB = "";
private static $instance; // stores the MySQLi instance
private function __construct() { } // block directly instantiating
private function __clone() { } // block cloning of the object
public static function call()
{
// create the instance if it does not exist
if(!isset(self::$instance))
{
// the MYSQL_* constants should be set to or
// replaced with your db connection details
self::$instance = new MySQLi(self::MYSQL_HOST, self::MYSQL_USER, self::MYSQL_PASS, self::MYSQL_DB);
if(self::$instance->connect_error)
{
throw new Exception('MySQL connection failed: ' . self::$instance->connect_error);
}
}
// return the instance
return self::$instance;
}
}
?>

Comments