Commit | Line | Data |
---|---|---|
2aa91ff2 S |
1 | <?php |
2 | namespace dns\system; | |
3 | ||
4 | /** | |
5 | * Basis class for singleton classes. | |
6 | * | |
7 | * @author Alexander Ebert | |
8 | * @copyright 2001-2014 WoltLab GmbH | |
9 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> | |
10 | * @package com.woltlab.wcf | |
11 | * @subpackage system | |
12 | * @category Community Framework | |
13 | */ | |
14 | abstract class SingletonFactory { | |
15 | /** | |
16 | * list of singletons | |
17 | * @var array<SingletonFactory> | |
18 | */ | |
19 | protected static $__singletonObjects = array(); | |
20 | ||
21 | /** | |
22 | * Singletons do not support a public constructor. Override init() if | |
23 | * your class needs to initialize components on creation. | |
24 | */ | |
25 | protected final function __construct() { | |
26 | $this->init(); | |
27 | } | |
28 | ||
29 | /** | |
30 | * Called within __construct(), override if neccessary. | |
31 | */ | |
32 | protected function init() { } | |
33 | ||
34 | /** | |
35 | * Object cloning is disallowed. | |
36 | */ | |
37 | protected final function __clone() { } | |
38 | ||
39 | /** | |
40 | * Object serializing is disallowed. | |
41 | */ | |
42 | public final function __sleep() { | |
43 | throw new \Exception('Serializing of Singletons is not allowed'); | |
44 | } | |
45 | ||
46 | /** | |
47 | * Returns an unique instance of current child class. | |
48 | * | |
49 | * @return \dns\system\SingletonFactory | |
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 \Exception("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 | } |