Implementing a Singleton using Traits
suggest changeDisclaimer: In no way does this example advocate the use of singletons. Singletons are to be used with a lot of care.
In PHP there is quite a standard way of implementing a singleton:
class Singleton {
private static ?self $instance = null;
private function __construct() {}
public static function getInstance(): self {
if (!self::$instance) {
// new self() is 'basically' equivalent to new Singleton()
self::$instance = new self();
}
return self::$instance;
}
// Cloning a private __clone is an Error
private function __clone(): void {}
// An empty __sleep does not stop serialize(). Throw so it fails.
public function __sleep(): array {
throw new \LogicException('Singleton cannot be serialized');
}
public function __wakeup(): void {
throw new \LogicException('Singleton cannot be unserialized');
}
}
To prevent code duplication, it is a good idea to extract this behaviour into a trait.
trait SingletonTrait {
private static ?self $instance = null;
protected function __construct() {}
public static function getInstance(): self {
if (!self::$instance) {
// new self() will refer to the class that uses the trait
self::$instance = new self();
}
return self::$instance;
}
private function __clone(): void {}
public function __sleep(): array {
throw new \LogicException('Singleton cannot be serialized');
}
public function __wakeup(): void {
throw new \LogicException('Singleton cannot be unserialized');
}
}
Now any class that wants to function as a singleton can simply use the trait:
class MyClass {
use SingletonTrait;
}
// Error! Constructor is not publicly accessible
$myClass = new MyClass();
$myClass = MyClass::getInstance();
// clone is an Error because __clone is private
$myClassCopy = clone $myClass;
// serialize() and unserialize() throw the LogicException from __sleep and __wakeup
$serializedMyClass = serialize($myClass);
$myClass = unserialize($serializedMyClass);
self in the trait refers to the class that uses the trait. A child that only inherits getInstance() receives the parent instance. Returning [] from __sleep still serializes the object with no properties. Throwing is what rejects it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents