How to maintain a single database object using php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to maintain a single database object using php

Post by Neo » Sun Feb 28, 2010 11:46 pm

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.

Code: Select all

<?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:

Code: Select all

$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.
Post Reply

Return to “PHP & MySQL”