Friday, February 14, 2025

PHP Creational Singelton

📁 File Structure

1. Singleton.php - This file contains the actual Singleton class.
2. index.php - This demonstrates the Singleton pattern in action.
3. SomeClass.php - An additional class to showcase how the Singleton can be used with other classes.
    

1. Singleton.php

<?php

class Singleton {
    private static $instance = null;

    // The constructor is private so that the object can't be instantiated from outside
    private function __construct() { }

    // Cloning is disabled to ensure the uniqueness of the instance
    private function __clone() { }

    // This method returns the singleton instance of this class
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

?>
    

2. SomeClass.php

<?php

class SomeClass {
    private $singleton;

    public function __construct() {
        $this->singleton = Singleton::getInstance();
    }

    public function doSomething() {
        echo "Using the Singleton instance within SomeClass!";
    }
}

?>
    

3. index.php

<?php

include 'Singleton.php';
include 'SomeClass.php';

// Trying to get two instances of Singleton
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

// Both instances are the same
if ($instance1 === $instance2) {
    echo "Both instances are the same!<br>";
}

// Demonstrating the use of Singleton in another class
$obj = new SomeClass();
$obj->doSomething();

?>
    

🛠 Explanation

  • Singleton Class:
    • Private static variable $instance: This holds the only instance of the class.
    • Private Constructor: To prevent any external instantiations.
    • Private __clone Method: To prevent the object from being cloned.
    • getInstance Method: Ensures only one instance is created.
  • SomeClass:
    • Demonstrates how we might use the Singleton within another class.
  • index.php:
    • Demonstrates that both instances retrieved from Singleton::getInstance() are the same.
    • Shows the usage of the Singleton instance within another class.

⚠️ Important Note

When working with the Singleton pattern, ensure you genuinely need a singleton. Overusing this pattern can lead to design issues and difficulties in testing.

No comments:

Abstract Factory Pattern in C#

Below is a C# implementation of the Abstract Factory design pattern, a Creational pattern, following the Gang of Four (GoF) structure....