Friday, November 30, 2007

MySQL Singleton Class with PHP5

The singleton can be use in lot of differents cases. In this exemple we will make a MySQL connection Singleton class. This will help us to always use the same connection.

class MysqlDB{
static private $instance_MysqlDB = null;

private
$objMysqli;

/**
* Instantiate the object
**/

private function __construct(){
$this->objMysqli = new mysqli("localhost", "root", "", "mysql");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
/**
* Perform a query
*
* @param string $sql
*/

public function select($sql){
$this->objMysqli->query($sql);
$this->var_dumping();
}
/**
* Var dump the current object
*/

public function var_dumping(){
var_dump($this);
}

/**
* Get the current instance for the object
*
* @return object
*/
static public function getInstance(){
if(self::$instance_MysqlDB == null){
self::$instance_MysqlDB = new self;
}
return self::$instance_MysqlDB;
}
}

---------------------------------------
To use the singleton we will never use the constructor method. We will call the getInstance method.
Here is an example :
include_once("MysqlDb.php");
MysqlDB::getInstance()->select("SELECT * FROM `help_category` LIMIT 5");

1 comment:

ray said...

Hi there,
I am interested in using OOP for PHP5, and would like singleton pattern for mysql connection.. as per what you have done. However, I am confused by your c() function which you use to close the mysql connection.. can you explain why you do not use the __destruct() function that I've read about.. wouldn't it be better if it auto closed itself after some time, rather than c() to close it manually? Just an inqury as I'm a php newbie. thanks! - ray