PHP 5 Design Pattern : Singleton

Let’s discover the design patterns and one of them, the Singleton.

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.

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");
MysqlDB::getInstance()->select("SELECT * FROM `help_keyword ` LIMIT 7");
MysqlDB::getInstance()->select("SELECT * FROM `help_category` LIMIT 7");
MysqlDB::getInstance()->select("SELECT * FROM `help_keyword ` LIMIT 5");

At the first call of MysqlDB::getInstance() the static private variable $instance_MysqlDB is set to Null. Si we will make a new instance of this object (new self) and save this instance in the $instance_MysqlDB variable.
Then when we will make more calls on this object we will use the same instance.

object(MysqlDB)#1 (1) {
 ["objMysqli:private"]=>
	object(mysqli)#2 (0) {}
}
object(MysqlDB)#1 (1) {
 ["objMysqli:private"]=>
 	object(mysqli)#2 (0) {}
}
object(MysqlDB)#1 (1) {
 ["objMysqli:private"]=>
 	object(mysqli)#2 (0) {}
}
object(MysqlDB)#1 (1) {
 ["objMysqli:private"]=>
 	object(mysqli)#2 (0) {}
}

About this entry