A PHP Interface for Singletons. See SingletonInterface.
composer require --dev "phptailors/singleton-interface:^1.0"
composer require --dev "phpunit/phpunit"A minimal implementation (example):
<?php
use Tailors\Lib\Singleton\SingletonInterface;
use Tailors\Lib\Singleton\SingletonException;
final class MySingleton implements SingletonInterface
{
private static ?MySingleton $instance = null;
public static function getInstance(): MySingleton
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {}
private function __clone() {}
public function __wakeup()
{
throw new SingletonException('Cannot unserialize singleton '.self::class);
}
}A real Singleton in PHP:
- Should NOT be extendable (should be
final). - Should have a private constructor (__construct()).
- Its
getInstance()should return a single instance of its class. - Should NOT be cloneable (__clone() should be a private method).
- Should always throw Tailors\Lib\Singleton\SingletonException on unserialize() (from __wakeup()).
The behavior of a Singleton may be tested using phptailors/singleton-testing.