The Singleton pattern is a design pattern that ensures that a class has only one instance and provides a global point of access to it. This is useful when you need to ensure that only one instance of a class exists, or when you want to provide a global point of access to the instance of a class.
Here is an example of how to implement the Singleton pattern in PHP:
class Singleton
{
private static $instance;
private function __construct()
{
// private constructor to prevent direct instantiation
}
public static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static();
}
return static::$instance;
}
}
The Singleton
class has a private constructor, which prevents the class from being directly instantiated. It also has a getInstance
method, which returns the single instance of the class. If the instance does not yet exist, the method creates it using the new
operator.
To use the Singleton
class, you can call the getInstance
method like this:
$singleton = Singleton::getInstance();
This will return the single instance of the Singleton
class. If the instance does not yet exist, the getInstance
method will create it. If the instance already exists, the method will simply return the existing instance.
The Singleton pattern is useful in situations where you want to ensure that only one instance of a class exists, or when you want to provide a global point of access to the instance of a class. It is a simple and effective way to manage the lifecycle of a class and ensure that it is used consistently throughout an application.
PHP Working Example :
https://github.com/vlpreddy/design-patterns-php/tree/main/singleton-patternTypescript Working Example :
https://github.com/vlpreddy/design-patterns-typescript/tree/main/singleton-patternan example implementation using php and typescript, used docker for creating server