What is singleton pattern

1. Intent

Ensure a class has only one instance throughout the application, and provide a global point of access to that instance.

2. Problem

  • Sometimes you need only one object to coordinate actions across the system.
  • Example issues if not controlled:
    • Multiple database connections waste resources.
    • Multiple logging instances cause inconsistent logs.
    • Multiple configuration objects can conflict.

3. Solution

  • Create a class that controls its own instantiation.
  • Ensure:
    • Only one instance exists.
    • It can be accessed globally (usually via a static method).

4. Real-World Analogy

Think of a President of a country:

  • A country can have only one president at a time.
  • Everyone refers to the same person when they say “the president”.
  • The system ensures no one can create a second president.

5. Structure

 -------------------------
|        Singleton        |
|-------------------------|
| - instance: Singleton   |   (private static)
|-------------------------|
| + getInstance(): Singleton |  (public static method)
 -------------------------

6. Pseudocode

class Singleton:
    private static instance = null

    private constructor() 
        // Prevent direct instantiation

    public static getInstance():
        if instance == null:
            instance = new Singleton()
        return instance

PHP Singleton Example

<?php
class Database {
    // Hold the single instance
    private static $instance = null;
    private $connection;

    // Private constructor to prevent multiple objects
    private function __construct() {
        $this->connection = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
        echo "New Database Connection Created\n";
    }

    // Prevent cloning
    private function __clone() { }

    // Prevent unserialization
    private function __wakeup() { }

    // Public static method to get the single instance
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    // Example query method
    public function query($sql) {
        return $this->connection->query($sql);
    }
}

// -------------------- USAGE --------------------

// First call → creates new instance
$db1 = Database::getInstance();

// Second call → returns the same instance (no new connection)
$db2 = Database::getInstance();

// Check if both are the same
if ($db1 === $db2) {
    echo "Both are the same instance ✅\n";
}

Simple PHP Singleton Example (Counter)

<?php
class Counter {
    private static $instance = null;  // only one instance
    private $count = 0;               // a simple variable

    // private constructor (no direct new Counter())
    private function __construct() { }

    // get the single instance
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Counter();
        }
        return self::$instance;
    }

    // increase counter
    public function increment() {
        $this->count++;
    }

    // get counter value
    public function getCount() {
        return $this->count;
    }
}

// ---------------- USAGE ----------------

// First object
$counter1 = Counter::getInstance();
$counter1->increment();
$counter1->increment();

// Second object (actually the same instance)
$counter2 = Counter::getInstance();
$counter2->increment();

// Check values
echo "Counter1: " . $counter1->getCount() . "\n"; // 3
echo "Counter2: " . $counter2->getCount() . "\n"; // 3

Leave a Reply

Your email address will not be published. Required fields are marked *