Aug/091
Snippet: Maintain a Single Database Object in PHP 5 Using the Singleton Pattern
When creating a PHP application, it is usually necessary to connect to a database to perform certain tasks. In some cases you only want to open a connection when necessary, but limit it to a single connection. This way you don't waste resources on unnecessary database connections. For these situations I use the Singleton Pattern, which is perfect for this.
In this example, we are creating a MySQLi object and forcing it to a single instance. We just need to call DB::get() to create and/or access the object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php class 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 get() { // 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(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB); if(self::$instance->connect_error) { throw new Exception('MySQL connection failed: ' . self::$instance->connect_error); } } // return the instance return self::$instance; } } ?> |
Calling the get() method statically will give you access to the MySQLi methods. Whenever you need to make a query, you just have to do this:
$result = DB::get()->query("SELECT * FROM ...");
So that is my preferred solution to the problem. Some people would argue that there are different ways to handle to problem, so I'd like to hear about any of these alternatives or improvements.

September 20th, 2009
Nice, thanks for posting this. I made a couple of changes and posted the code up over at http://www.davecomeau.net/blog/1/Single+Database+Object+in+PHP+5+Using+the+Singleton+Pattern