Design pattern in PHP: Singleton Pattern

The singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance.

The singleton pattern is one of the simplest patterns and is usually one of the most commonly used patterns. In singleton pattern, a class can only be instantiated one time.

What singleton pattern can do?

When we want to control the number of instances or save system resources globally, singleton pattern is a good choice which avoid a class being created and destroyed frequently.

Implementation

Let’s see an example of singleton pattern in PHP.

Step 1: Create a singleton class

/**
 * a singleton class
 */
class Singleton
{
	/**
	 * property
	 * @var array
	 */
	private $props = []; 

	/**
	 * a static variable to store itself
	 * @var null
	 */
	private static $instance = null;

	/**
	 * construct method is private. It means you can't constuct this class from outside
	 * this is a key method to singleton pattern
	 */
    private function __construct()
    {
    	// do nothing
    }

    /**
     * return a self instance
     * 
     * @return Singleton
     */
    public static function getInstance()
    {
    	if (null === self::$instance) {
    		self::$instance = new self();
    	}

    	return self::$instance;
    }

    /**
     * set property
     * @param mixed $key
     * @param mixed $val
     *
     * @return  void
     */
    public function setProperty($key, $val)
    { 
        $this->props[$key] = $val; 
    } 

    /**
     * get paoterty
     * @param  mixed $key
     * 
     * @return mixed
     */
    public function getProperty($key)
    { 
        return isset($this->props[$key]) ? $this->props[$key] : null; 
    } 
}

Step 2: create an instance

$singleton = Singleton::getInstance();
$singleton->setProperty('myvar', 'i am a single instance');
echo $singleton->getProperty('myvar');

Step 3: run the script and check the result

$ php singleton.php
i am a single instance

Here is a typical singleton class in php which can only be created inside because the construct method is defined as private method and the only way to get an instance is through static method: Single::getInstance().

Pros of singleton pattern

  1. There is only one instance in memory, which reduces the memory overhead, especially the frequent creation and destruction of instances.
  2. Avoid multiple occupation of resources (such as database connection, config of our application).

Cons of visitor pattern

  1. The responsibilities of the singleton category are too heavy, which violates the “single responsibility principle” to a certain degree.
  2. It is not suitable for changing objects. If an object always changes in different scenarios, the singleton will trigger data errors sometimes.

RSS