5 use wcf\system\exception\SystemException
;
8 * Base class for singleton factories.
10 * @author Alexander Ebert
11 * @copyright 2001-2019 WoltLab GmbH
12 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
14 abstract class SingletonFactory
18 * @var SingletonFactory[]
20 protected static $__singletonObjects = [];
23 * Singletons do not support a public constructor. Override init() if
24 * your class needs to initialize components on creation.
26 final protected function __construct()
32 * Called within __construct(), override if necessary.
34 protected function init()
39 * Object cloning is disallowed.
41 final protected function __clone()
46 * Object serializing is disallowed.
48 final public function __sleep()
50 throw new SystemException('Serializing of Singletons is not allowed');
54 * Returns an unique instance of current child class.
57 * @throws SystemException
59 final public static function getInstance()
61 $className = static::class;
62 if (!isset(self
::$__singletonObjects[$className])) {
63 // The previously used `null` value forced us into using `array_key_exists()` which has a bad performance,
64 // especially with the growing list of derived classes that are used today. Saves a few ms on every request.
65 self
::$__singletonObjects[$className] = false;
66 self
::$__singletonObjects[$className] = new $className();
67 } elseif (self
::$__singletonObjects[$className] === false) {
68 throw new SystemException(
69 "Infinite loop detected while trying to retrieve object for '" . $className . "'"
73 return self
::$__singletonObjects[$className];
77 * Returns whether this singleton is already initialized.
81 final public static function isInitialized()
83 $className = static::class;
85 return isset(self
::$__singletonObjects[$className]);