Singleton in PHP

Singleton in PHP

One of the commonly utilized part in programming is database access. Accessing a database in PHP is by far tied with his beloved one: MySQL.

While connecting and working with database, we have to limit the number of connections to database. Especially in a single database environment, the program shall utilize one object efficiently for all of its actions. Resource management and efficiency would be increased in doing so.

I have tried to apply the singleton pattern on the database class and share it here.
I have an interface with the following signature:


/* An interface for database.  
Author: http://gullele.com
Open for any modification and usage
Date: 18.Apr.2009
*/
	interface IDatabase{
		/* method for connection */
		public function connect();
		/* method for opening the database */
		public function open();
		/* method for closing */
		public function close();
		/* method for query that returns result - common for other kind of databases like SQL Server */
		public function executeQuery($query);
		/* method for query that does not return result */	
		public function executeNonQuery($query);
		public static function getInstance(); /*function to return a static instance of a class*/
	}

This interface would assure all the implementers would have the same functions all over.
If we have this, later, if we change the database – those methods who have been using the database class would remain unaffected.

Here is the mysql database which implements the interface and the logic of singleton pattern is applied.


/*
Author: http://gullele.com
Open for modification and any use - please let me know when you use/modify it as I might learn from your modification. 
Date: 18.Apr.2009
*/
class Mysql implements IDatabase{
		private $host; 
		private $username;
		private $password;
		private $db_name;
                private $connection_error;
		private static $instance = null; /*an instance of the class*/
		/* Connection object to be assigned for the database selected */
		private $connection; 
		/* Make the constructor private or protected to prevent the object from being instantiated directly - this is how to make it singleton pattern being applied*/
		private function __construct(){
			$this->host = 'localhost';		
			$this->username = 'root';
			$this->password = 'root';
			$this->db_name = 'intramicro';
			$this->connect();
		}
		/* Connecting to the database it also opens the database */
		public function connect(){

        		if (!$this->connection = @mysql_connect($this->host,

                            $this->username,$this->password)) {
	    			echo "Connection error";

            			trigger_error('Error Connection to database');

            			$this->connect_error=true;

        		/* Assing to the database for initial use - can be changed later if needed */

        		} else if ( !@mysql_select_db($this->db_name,$this->connection) ) {

            		trigger_error('Database selection error');

            		$this->connect_error=true;

        		}		
		}
		/* Implementation is not needed for this method as mysql would open the database when it connects to it */
		public function open(){
		}
		/* Closing the database - used for non-persistent connection*/
		public function close(){
			mysql_close($this->connection);		
		}
		/* A method to accept query object, execute it and return resource object */
		public function executeQuery($query){
			if (!$query_resource=mysql_query($query,$this->connection))

            			trigger_error ('Query failed: '.mysql_error($this->connection).' SQL: '.$query);	
			return $query_resource;
		}
		/* Non query method is not needed in the MySQL database as it can be done with my_sql()*/
		public function executeNonQuery($query){}
		public static function getInstance(){
			if(is_null($instance))
				self::$instance=new self();
			return self::$instance;
		}
	}

It is necessary to make the constructor of the implementing class private or protected to inhibit the direct instantiation of the object from the clients.
The clients shall know enjoying the object of MySQL class would only through the static getInstance() method of the class.

Here is an example

require(‘…MySQL.Database.php’); //include the file here
$objDb=Mysql::getInstance(); //get instance here
Once it is instantiated, a single object would serve for many clients.
You may want to check the security, error handling and some additional things by your own.
Cool..

See how you would solve these known algorithm problems

Implementing tokenizer and adding tokens to the linked list

Java solution for checking anagram strings – tell if phrases are anagrams

String Ordered Permutation Algorithm Problem

Finding missing numbers from billion sequential number list file

Check if there are three numbers a, b, c giving a total T from array A

Implement Queue Using two Stacks – JavaScript algorithm

Find the first occurence of number in the sorted array

testing k complementary pairs algorithm with junit

Find K Complementary numbers from array Java implementation

Kadane’s algorithm in C – Dynamic Programming

One Comment
  1. Encapsulating Queries in Object « Gullele’s Corner

    […] can get Mysql class in the singleton pattern part of my article. Possibly related posts: (automatically generated)Singleton in […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*