byjg/singleton-pattern

A lightweight PHP implementation of the Design Pattern Singleton using trait.

Fund package maintenance!
byjg

Installs: 53 559

Dependents: 2

Suggesters: 0

Security: 0

Stars: 9

Watchers: 2

Forks: 3

Open Issues: 0

pkg:composer/byjg/singleton-pattern

5.0.0 2024-10-27 16:15 UTC

This package is auto-updated.

Last update: 2025-11-19 05:19:49 UTC


README

Build Status Opensource ByJG GitHub source GitHub license GitHub release

Singleton Pattern

A lightweight PHP implementation of the Design Pattern Singleton using trait. Just one class and no dependencies.

Requirements

PHP 8.1 or higher

Installation

composer require "byjg/singleton-pattern"

Creating a Singleton Class

<?php
require "vendor/autoload.php";

class Example
{
    // Use the Singleton trait to implement the pattern
    use \ByJG\DesignPattern\Singleton;
    
    // You can add properties to your singleton
    public string $someProperty;
    
    // The constructor MUST be private or protected
    private function __construct()
    {
        // Optional initialization code
        $this->someProperty = "Initial value";
    }
    
    // Add your own methods and properties here
    public function doSomething(): void
    {
        // Your code here
    }
}

IMPORTANT:

  1. Your class MUST use a private or protected constructor.
  2. Singleton classes do not accept arguments in the constructor.
  3. Attempting to clone, serialize, or unserialize a singleton will throw a SingletonException.

Using your Singleton class

// Get the singleton instance
$example = Example::getInstance();

// The same instance is always returned
$anotherReference = Example::getInstance();
$example->someProperty = "Changed value";

// This will output "Changed value" because both variables reference the same instance
echo $anotherReference->someProperty;

// This will throw a SingletonException
try {
    $cloned = clone $example;
} catch (\ByJG\DesignPattern\SingletonException $e) {
    echo "Cannot clone a singleton!";
}

How It Works

The Singleton trait:

  • Implements the getInstance() static method to create and manage a single instance
  • Prevents cloning by overriding the __clone() method
  • Prevents serialization and deserialization by overriding __sleep() and __wakeup()
  • Uses a static property to store instances of each class that uses the trait

Run Tests

vendor/bin/phpunit

References

Dependencies

flowchart TD
    byjg/singleton-pattern
Loading

Open source ByJG