Understanding and Implementing the Singleton Pattern in PHP

Understanding and Implementing the Singleton Pattern

Welcome to the first lesson in our Creational Design Patterns course. We are starting with a powerful and widely used pattern: the Singleton Pattern. This pattern helps ensure that a class has only one instance and provides a global point of access to it. Understanding this pattern is a fantastic first step on your journey to mastering creational design patterns.

What You'll Learn

In this lesson, you'll learn how to implement the Singleton Pattern in PHP. We'll cover the following key points:

  1. Creating a Singleton Class: We'll explore how to construct a Singleton class, ensuring it has exactly one instance.
  2. Accessing the Singleton Instance: You'll learn how to create a global access point to this single instance.

Here's a sneak peek of the code you'll be working with:

PHP
<?php

class Logger {
    // Static method to access the single instance
    public static function getInstance() {
        static $instance = null;
        if ($instance === null) {
            $instance = new Logger();
        }
        return $instance;
    }

    // Log a message to the console
    public function log($message) {
        echo $message . PHP_EOL;
    }

    private function __construct() {} // Private constructor to prevent external instantiation
    private function __clone() {} // Disabled clone method
}

$logger = Logger::getInstance();
$logger->log("Singleton pattern example with Logger.");

$logger2 = Logger::getInstance();
$logger2->log("Looging using the second logger.");

// Alternatively, you can use the identity comparison
if ($logger === $logger2) {
    echo "Both logger instances are the same." . PHP_EOL;
} else {
    echo "Logger instances are different." . PHP_EOL;
}

// $otherLogger = Logger(); Error, since there is no public constructor
?>

In this snippet, you can see how we ensure that only one Logger instance is created and how we access it globally. We achieve this by defining a getInstance method that returns the single instance of the Logger class.

These are the essential parts of the Singleton Pattern:

  • Private Constructor: The constructor is private to prevent external instantiation of the class.
  • Static Method: A static getInstance method is used to access the single instance of the class without creating a new object.
  • Static Member: A static member variable holds a single instance of the class within a method using static scope.
  • Disabled Methods for Cloning and Serializing: The clone and wakeup methods are made private to prevent duplicate instances from being created through these operations.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal