Design patterns: Singleton

date: · 2 min
author: Mauto
series: Design Patterns/ part 2/24

The classic Gang of Four patterns, one per part, with practical PHP examples.

  1. Design Patterns
  2. Design patterns: Singleton
  3. Design patterns: Factory Method
  4. Design patterns: Abstract Factory
  5. Design patterns: Builder
  6. Design patterns: Prototype
  7. Design patterns: Adapter
  8. Bridge Pattern in PHP: What It Is, When to Use It, with Examples
  9. Design patterns: Composite
  10. Design patterns: Decorator
  11. Design patterns: Facade, What It Is and How to Use It (PHP)
  12. Design patterns: Flyweight
  13. Design patterns: Proxy
  14. Design patterns: Chain of Responsibility Explained (PHP)
  15. Design patterns: Command
  16. Design patterns: Interpreter
  17. Design patterns: Iterator
  18. Design patterns: Mediator
  19. Design patterns: Memento
  20. Design patterns: Observer
  21. Design patterns: State, What It Is and How to Use It (PHP)
  22. Design patterns: Strategy
  23. Design patterns: Template Method
  24. Design patterns: Visitor
the whole guide >

The Singleton Pattern is a creational pattern used to ensure that a class has only one instance and provides a global point of access to that instance. This pattern is useful in situations where having multiple instances of a class could cause problems, consume too many resources, or simply make no sense.

Characteristics of the Singleton pattern

  1. Private constructor: Prevents the creation of multiple instances of the class
  2. Static getInstance() method: Checks whether an instance of the class already exists; if not, it creates a new one.
  3. Single instance: Every time getInstance() is called, it always returns the same instance, guaranteeing that there is only one.
  4. Cloning and unserialization forbidden: The pattern blocks cloning and unserialization, preventing the singleton instance from being duplicated.

PHP Example:

class Singleton {
    private static $instance;

    // The constructor is private to prevent the use of "new"
    private function __construct() {} 

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
    
    // Prevents cloning of the instance
    private function __clone() {}

    // Prevents unserialization of the instance (since PHP 8 __wakeup must be public)
    public function __wakeup() {
        throw new \Exception("A singleton cannot be unserialized");
    }
}

// Usage
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

echo $instance1 === $instance2 ? "Same instance" : "Different instances";

Common use case

Imagine you’re developing an application that interacts with a database. Opening a database connection is expensive and, if every component opens its own, you risk performance problems, resource management issues, or even errors. In this context, the Singleton is useful because it guarantees that only one database connection is open.

BACK TO THE GUIDE

Copied