byjg/singleton-pattern

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

Maintainers

Package info

github.com/byjg/php-singleton-pattern

pkg:composer/byjg/singleton-pattern

Fund package maintenance!

byjg

Statistics

Installs: 55 129

Dependents: 2

Suggesters: 0

Stars: 10

Open Issues: 0

6.0.0 2025-11-25 03:47 UTC

This package is auto-updated.

Last update: 2026-03-10 17:58:34 UTC


README

sidebar_key tags
singleton-pattern
php

Singleton Pattern

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

Sponsor Build Status Opensource ByJG GitHub source GitHub license GitHub release

Documentation

Requirements

PHP 8.3 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 local variable within getInstance() 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