Tuesday, April 06, 2010

PHP5 DB Connection Class with MYSQLi using Singleton!

Thought it would be a good idea to share my database connection class with you all, which I use in my apps. I have implemented this class in Singleton Design Pattern.
Use of this class will help you to manage the database connection of your PHP5 application, and will avoiding you and/or your programmers creating more and more DB connection instances, that will make your code more complicated and disorganized.

As a result of using Singleton Design Pattern, no one will be able to create more than one instance of the class. So whenever anyone tries  to create an object of this class, they will either get a new object when it is the first time you are creating an object of this class, else you will always get a DB Connection instance which has already begin created.

I have made this class little bit simple to help everyone could understand it and to use when ever you need it.

Here is the code,
 /*PHP5 MYSQLi DB Connection Class implementing Singleton Design Pattern
 * 
 * Author  : Thanura Siribaddana
 * Date    : 05-APR-2010
 * Web Site: www.thanura.com
 * 
 *  Usage:
 *   $db = DBAccess::getConnection();
 *   $query = "select * from TABLE";
 *   $result=$db->selectQuery($query);
 */
error_reporting(E_NOTICE);

class DBAccess{

 const DB_SERVER="localhost"; 
 const DB_USER="root";
 const DB_PASS="pass";
 const DB_NAME="dbname";
 
 private $_connection;
 private static $_dbinstance;

/* Made the constructor private, 
* to ensures that the class can only be instantiated 
* from within itself.
*/
 private function __construct(){
  try{
   $this->_connection= new mysqli(self::DB_SERVER,
                                     self::DB_USER,
                                     self::DB_PASS,
                                     self::DB_NAME);
   if ($this->_connection->connect_error){
       throw new Exception("Could not connect to Database.");
   }
  }catch(Exception $err){
   echo $err->getMessage();
   die();
  }
  
 }
 public static function getConnection(){
  if (is_null(self::$_dbinstance)){
   self::$_dbinstance= new DBAccess();
  }
  return self::$_dbinstance;
 }
 /* Execute a SQL query and returns the results*/
 public function selectQuery($query){
  $rs=$this->_connection->query($query);
  return $rs; 
 }
}

All comments welcome!! For fine-tuning... For better ideas... any thing...