Commit | Line | Data |
---|---|---|
11ade432 | 1 | <?php |
308c880f | 2 | declare(strict_types=1); |
11ade432 | 3 | namespace wcf\system; |
32baee20 | 4 | use wcf\system\exception\SystemException; |
11ade432 AE |
5 | |
6 | /** | |
8aacc17d | 7 | * Base class for singleton factories. |
f341086b | 8 | * |
11ade432 | 9 | * @author Alexander Ebert |
c839bd49 | 10 | * @copyright 2001-2018 WoltLab GmbH |
11ade432 | 11 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> |
e71525e4 | 12 | * @package WoltLabSuite\Core\System |
11ade432 AE |
13 | */ |
14 | abstract class SingletonFactory { | |
f341086b AE |
15 | /** |
16 | * list of singletons | |
893aace3 | 17 | * @var SingletonFactory[] |
f341086b | 18 | */ |
058cbd6a | 19 | protected static $__singletonObjects = []; |
f341086b | 20 | |
11ade432 AE |
21 | /** |
22 | * Singletons do not support a public constructor. Override init() if | |
23 | * your class needs to initialize components on creation. | |
24 | */ | |
f341086b | 25 | protected final function __construct() { |
11ade432 AE |
26 | $this->init(); |
27 | } | |
28 | ||
29 | /** | |
b2aa772d | 30 | * Called within __construct(), override if necessary. |
d726f13d | 31 | */ |
11ade432 AE |
32 | protected function init() { } |
33 | ||
34 | /** | |
35 | * Object cloning is disallowed. | |
36 | */ | |
37 | protected final function __clone() { } | |
38 | ||
32baee20 TD |
39 | /** |
40 | * Object serializing is disallowed. | |
41 | */ | |
42 | public final function __sleep() { | |
43 | throw new SystemException('Serializing of Singletons is not allowed'); | |
32baee20 TD |
44 | } |
45 | ||
11ade432 AE |
46 | /** |
47 | * Returns an unique instance of current child class. | |
f341086b | 48 | * |
d0fe02fc | 49 | * @return static |
2b770bdd | 50 | * @throws SystemException |
11ade432 AE |
51 | */ |
52 | public static final function getInstance() { | |
f341086b AE |
53 | $className = get_called_class(); |
54 | if (!array_key_exists($className, self::$__singletonObjects)) { | |
55 | self::$__singletonObjects[$className] = null; | |
56 | self::$__singletonObjects[$className] = new $className(); | |
57 | } | |
58 | else if (self::$__singletonObjects[$className] === null) { | |
59 | throw new SystemException("Infinite loop detected while trying to retrieve object for '".$className."'"); | |
60 | } | |
61 | ||
62 | return self::$__singletonObjects[$className]; | |
63 | } | |
64 | ||
65 | /** | |
66 | * Returns whether this singleton is already initialized. | |
67 | * | |
68 | * @return boolean | |
69 | */ | |
70 | public static final function isInitialized() { | |
71 | $className = get_called_class(); | |
72 | ||
73 | return isset(self::$__singletonObjects[$className]); | |
96e82a73 | 74 | } |
11ade432 | 75 | } |