-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Singleton.php
87 lines (73 loc) · 1.97 KB
/
Singleton.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* @author Marwan Al-Soltany <MarwanAlsoltany@gmail.com>
* @copyright Marwan Al-Soltany 2020
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MAKS\AmqpAgent\Helper;
use MAKS\AmqpAgent\Exception\SingletonViolationException;
/**
* An abstract class implementing the fundamental functionality of a singleton.
* @since 1.0.0
*/
abstract class Singleton
{
/**
* Each sub-class of the Singleton stores its own instance here.
* @var array
*/
private static $instances = [];
/**
* Can't be private if we want to allow sub-classing.
*/
protected function __construct()
{
//
}
/**
* Cloning is not permitted for singletons.
*/
public function __clone()
{
throw new SingletonViolationException("Bad call. Cannot clone a singleton!");
}
/**
* Serialization is not permitted for singletons.
*/
public function __sleep()
{
throw new SingletonViolationException("Bad call. Cannot serialize a singleton!");
}
/**
* Unserialization is not permitted for singletons.
*/
public function __wakeup()
{
throw new SingletonViolationException("Bad call. Cannot unserialize a singleton!");
}
/**
* The method used to get the singleton's instance.
* @return self
*/
public static function getInstance()
{
$subclass = static::class;
if (!isset(self::$instances[$subclass])) {
self::$instances[$subclass] = new static();
}
return self::$instances[$subclass];
}
/**
* Destroys the singleton's instance it was called on.
* @param self &$object The instance it was called on.
* @return void
*/
public function destroyInstance(&$object)
{
if (is_subclass_of($object, __CLASS__)) {
$object = null;
}
}
}