byjg/singleton-pattern

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

Maintainers

👁 byjg

Package info

github.com/byjg/php-singleton-pattern

pkg:composer/byjg/singleton-pattern

Fund package maintenance!

byjg

Statistics

Installs: 56 936

Dependents: 2

Suggesters: 0

Stars: 10

Open Issues: 0

6.0.0 2025-11-25 03:47 UTC

Requires

  • php: >=8.3 <8.6

Requires (Dev)

Suggests

None

Provides

None

Conflicts

None

Replaces

None

MIT 15bb94ebd3dcc2374c35d63ebc28f721f71ed029

This package is auto-updated.

Last update: 2026-06-10 18:30:13 UTC


README

sidebar_key singleton-pattern
tags
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