1
|
|
|
<?php |
2
|
|
|
namespace Fwolf\Base\Singleton; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Trait of object which SHOULD have only one instance |
6
|
|
|
* |
7
|
|
|
* |
8
|
|
|
* Singleton or container classes commonly have only one instance, and a |
9
|
|
|
* static getInstance() method are used to create and return its instance. |
10
|
|
|
* |
11
|
|
|
* For reuse only, should not use as type hint, so no relevant interface. |
12
|
|
|
* |
13
|
|
|
* The difference between this and singleton is, this mode does not strictly |
14
|
|
|
* prohibit multiple instances, target on consume less resources. |
15
|
|
|
* |
16
|
|
|
* Can not use when constructor need parameters. |
17
|
|
|
* |
18
|
|
|
* |
19
|
|
|
* Notice: If a class Foo use this trait, then extend by child class Bar, the |
20
|
|
|
* Bar class may need use this trait too, because 'static' is bind to Foo(the |
21
|
|
|
* class which trait is used in). For work properly, Bar need its own static |
22
|
|
|
* method -- use this trait too. |
23
|
|
|
* |
24
|
|
|
* Copy getInstance() to class use this trait may work, only when parent class |
25
|
|
|
* Foo is not used/instanced before it. If Foo::getInstance() is called before |
26
|
|
|
* Bar::getInstance(), the static instance is generated in Foo, and skipped in |
27
|
|
|
* Bar, we will got a wrong instance type. This also happen when Bar is used |
28
|
|
|
* first. |
29
|
|
|
* |
30
|
|
|
* Another solution is make static instance as array, stores every instance |
31
|
|
|
* it is called in, with get_called_class() as index, here use this one. |
32
|
|
|
* |
33
|
|
|
* Make static instance property of class instead of method may also works, |
34
|
|
|
* but this property may cause name conflict with other property in child |
35
|
|
|
* class. Choose a good name when using this plan. |
36
|
|
|
* |
37
|
|
|
* |
38
|
|
|
* @see https://bugs.php.net/bug.php?id=65039 |
39
|
|
|
* @see http://php.net/manual/en/language.oop5.late-static-bindings.php |
40
|
|
|
* |
41
|
|
|
* |
42
|
|
|
* @copyright Copyright 2015-2016 Fwolf |
43
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
44
|
|
|
*/ |
45
|
|
|
trait SingleInstanceTrait |
46
|
|
|
{ |
47
|
|
|
/** |
48
|
|
|
* Get or reuse instance of self |
49
|
|
|
* |
50
|
|
|
* @return static |
51
|
|
|
*/ |
52
|
|
|
public static function getInstance() |
53
|
|
|
{ |
54
|
|
|
static $instances = []; |
55
|
|
|
|
56
|
|
|
$className = get_called_class(); |
57
|
|
|
|
58
|
|
|
if (!isset($instances[$className])) { |
59
|
|
|
$instances[$className] = new $className(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $instances[$className]; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|