⬆️ ⬇️

PHP Patterns: Singleton

Singleton



Introduction



Singleton is one of the easiest templates to understand. The main purpose is to ensure the existence of only one instance of the class. The reason is usually the following: only one object of the original class is required and you need the object to be available anywhere in the application, i.e. global access.



An example is the class for storing Settings. Settings class is a good example of the Singleton template, because its data is not changed (the only way to change the settings is to edit the settings file) and is often used in different parts of the application. In addition, creating new objects of the Settings class, where necessary, requires resources, which is wasteful, because objects will be identical.



Definition



The Singleton template assumes the presence of a static method for creating an instance of a class, when referencing which returns a reference to the original object.



PHP5 Example



PHP5 example (without implementing specific methods of the Settings class)

class Settings {

private $settings = array();

private static $_instance = null;

private function __construct() {

// getInstance ()

}

protected function __clone() {

//

}

static public function getInstance() {

if(is_null(self::$_instance))

{

self::$_instance = new self();

}

return self::$_instance;

}

public function import() {

// ...

}

public function get() {

// ...

}

}



')

Singleton pattern implementation



The key to implementing the Singleton pattern is a static variable, the variable whose value remains unchanged when executing behind its boundaries. This allows you to keep the object original between calls to the static method Settings :: getInstance (), and return a reference to it every time you call the method.

Keep in mind that the constructor is usually private. To ensure that only one Settings object is always used, we need to restrict access to the constructor, so that when we try to create a new object, an error will occur. It should also be borne in mind that these restrictions are not possible in PHP4.

Source: https://habr.com/ru/post/31375/



All Articles