PHP Design Patterns – The Singleton

Over the next few weeks I will be looking at design patterns used in PHP and will give real world examples of when to use them. I will also explain these in simple terms avoiding the jargon where possible so any one can understand.

The singleton as its name suggests is an object that when instantiated will only ever return a single instance of the object. The singleton should be used when you will only ever require a single instance of an object and do not want duplicates. The most widely used example of the singleton is in the database object. Once you have instantiated the database you do not want to re instantiate the object multiple times so when you need the database object, it will always look to see it an object of this type exists already and return that instead of a new object.

Below is the PHP code for the database singleton I use.

 
	class config
	{
		const DB_USER_NAME 	= "userName";
		const DB_PASSWORD	= "mySecret";
		const DB_HOST		= "localhost";
		const DB_NAME		= "myDatabase";
	}
	
	final class database extends config
	{
		private static $connection;
		private static $database;
		
		/* 
		* When dealing with singletons, we do not want the user to be able 
		* to instantiate a new object or we don't want them to be able to 
		* clone and create a new instance of the object. To mitigate this we 
		* must create the magic methods and either throw an error when these are 
		* called on in this example just do nothing.
		*/
		final private function __construct() {}
		final private function __clone() { }
		
		public static function getInstance() 
		{
			/* 
			* When getting the instance what we first do is find out if an instance 
			* already exists
			*/
			if (!(self::$database instanceof self))
			{
				/*
				* if this instance does not exist and this is the first we are seeing 
				* of it, we instantiate a new object
				*/
				self::$database = new self();
				self::dbConnect();
			}
	 
			/*
			* If this object does exists, don't create a new one, just simply return 
			* the object we have already.
			*/
			return self::$database;
		}
		
		/* 
		* I will now add the database specific code to create a new instance of the 
		* database using mysqli the code below makes an assumption that you are using 
		* mysqli, can be changed to any other DB type. It also assumes that you have 
		* exception handling, errors can be printed easily by changing 
		* 'throw new dbException' to 'print_r'
		*/
		private static function dbConnect()
		{
			self::$connection = new mysqli 
			( 
				parent::DB_HOST, 
				parent::DB_USER_NAME, 
				parent::DB_PASSWORD, 
				parent::DB_NAME
			); 
			 
			if (mysqli_connect_errno()) 
			{ 
				throw new dbException("Connection Error: %s\n ". mysqli_connect_error()); 
			} 
		}	
	
	}
	
	$database = database::getInstance(); 
	var_dump($database);
Share

One thought on “PHP Design Patterns – The Singleton

  1. And that would meen a roundtrip to a file on the client, or the database on the server. It seems pretty lame, that you cannot simply store a single instance of an object in a server variable.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.