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