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
Requires
- php: >=8.1 <8.4
Requires (Dev)
- phpunit/phpunit: ^9.6
- vimeo/psalm: ^5.9
README
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:
- Your class MUST use a private or protected constructor.
- Singleton classes do not accept arguments in the constructor.
- 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