The Singleton Design Pattern

Posted on December 29, 2011 by

The singleton design pattern is one of the easiest patterns that someone can use. Basically, it lets you create one single object (a singleton) that is used during the execution of your code. This means that no matter how many times you try to create a new one, you’ll just get the first one you originally created.

Why Would I do this?

The main reason to use a singleton pattern is to ensure that you’re not accidentally creating new objects throughout your code which uses system resources. If your objects are big memory hogs, the more you create the greater the risk that you will use up the memory allotted to your application (check out the memory_limit variable in your php.ini file to find out how much you’re allowed to use).

The other reason is to keep your code clean. Minimizing the amount of objects you create reduces the chances of harder to detect bugs.

For example, if you create an object called $tom, assigning it the name “Tom Jones” and an age of “65″; and later in your code, by accident, create another $tom object without assigning name and age values, you lose the values from the first.

When this happens, you’re left scratching your head as to why the name and age don’t appear like you expected; not realizing that you erased the values because you kind of overwrote it.

A Classic Example: Database Connection

One great example of why to use a singleton pattern is with a database connection. Think about it, for most web applications only one database is being used. In these situations you would only want to create one database connection once and use this connection throughout your code.

How do I do this?

Simple, follow the code below (the commenting is a little over the top for explanation purposes only):

/* Database Class using the Singleton Design Pattern; inheriting from the
	   PDO (PHP Data Object) */
	class Database extends PDO {
		private static $_db = null; // This is where we store our connection.
	
		/**
		 *  Constructor
		 *  This function calls the PDO constructor to connect to the database.
		 *  It's private which means that it can only be called within the
		 *  Database class itself.
		 */
		private function __construct() {
			parent::__construct([DB Server], [DB Username], [DB Password]);
		} // end of constructor
	
		/**
		 *  getInstance
		 *  This function is used by your code to either create the database
		 *  connection object; or, pass you back the one that was first created
		 *  (which is stored in the $_db variable).
		 *
		 *  It's static so that you don't need to create an instance of
		 *  Database - you can just call Database::getInstance();
		 *
		 * @return Database object
		 */
		public static function getInstance() {
			if (self::$_db instanceof Database) { return $_db; }
	
			self::$_db = new Database();
			return self::$_db;
		} // end of getInstance
	} // end of Database class

In our code, to create an instance of the database connection, we would write the following:

$db_connection = Database::getInstance();

What this Means

So no matter how many times we might call the $db_connection = Database::getInstance() code, we will always be returned one connection which ensures that we are not accidentally creating new connections throughout our code. Again, this is important as it reduces the amount of system resources we use in our applications and avoids potential bugs that we might not catch until it’s too late.

In Summary

The Singleton design pattern is a good pattern to use when you only need one instance of an object. Be wary for scalability though. If you ever get the inkling that your object may need to be broken up into two instances (like having two databases; one for reading and another for writing) then tread with caution.