Merge branch '3.0'
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / system / SingletonFactory.class.php
1 <?php
2 namespace wcf\system;
3 use wcf\system\exception\SystemException;
4
5 /**
6 * Base class for singleton factories.
7 *
8 * @author Alexander Ebert
9 * @copyright 2001-2018 WoltLab GmbH
10 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
11 * @package WoltLabSuite\Core\System
12 */
13 abstract class SingletonFactory {
14 /**
15 * list of singletons
16 * @var SingletonFactory[]
17 */
18 protected static $__singletonObjects = [];
19
20 /**
21 * Singletons do not support a public constructor. Override init() if
22 * your class needs to initialize components on creation.
23 */
24 protected final function __construct() {
25 $this->init();
26 }
27
28 /**
29 * Called within __construct(), override if necessary.
30 */
31 protected function init() { }
32
33 /**
34 * Object cloning is disallowed.
35 */
36 protected final function __clone() { }
37
38 /**
39 * Object serializing is disallowed.
40 */
41 public final function __sleep() {
42 throw new SystemException('Serializing of Singletons is not allowed');
43 }
44
45 /**
46 * Returns an unique instance of current child class.
47 *
48 * @return static
49 * @throws SystemException
50 */
51 public static final function getInstance() {
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]);
73 }
74 }