-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonTrait.php
More file actions
102 lines (89 loc) · 2.41 KB
/
SingletonTrait.php
File metadata and controls
102 lines (89 loc) · 2.41 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
/**
* This file is part of Blitz PHP framework.
*
* (c) 2022 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace BlitzPHP\Traits;
use RuntimeException;
/**
* Ce trait fournit le modèle Singleton (une seule instance pour la classe concrète) aux classes qui l'utilisent.
* Toute l'application entière peut accepter sa seule instance via la méthode statique publique getInstance(),
* fourni par le trait.
* Si quelqu'un essaie de cloner ou de sérialiser l'objet, le trait lève RuntimeException.
* La propriété statique pour la seule instance est déclarée comme protégée et est instanciée avec le mot-clé 'static'
* pour assurer la possibilité d'étendre la classe.
*/
trait SingletonTrait
{
/**
* La seule instance d'utilisation de la classe
*
* @var object
*/
protected static $_instance;
/**
* Vérifie, instancie et renvoie la seule instance de la classe appelée.
*
* @return static
*/
public static function instance()
{
if (! (static::$_instance instanceof static)) {
$params = func_get_args();
static::$_instance = new static(...$params);
}
return static::$_instance;
}
/**
* @alias instance
*/
public static function getInstance()
{
$params = func_get_args();
return static::instance(...$params);
}
/**
* Reinitialise l'instance
*/
public static function reset(): void
{
static::$_instance = null;
}
/**
* Constructeur de classe. La classe concrète utilisant ce trait peut le remplacer.
*/
protected function __construct()
{
}
/**
* Empêche le clonage des objets
*
* @throws RuntimeException
*/
public function __clone()
{
throw new RuntimeException('Cannot clone Singleton objects');
}
/**
* Empêche la sérialisation des objets
*
* @throws RuntimeException
*/
public function __sleep()
{
throw new RuntimeException('Cannot serialize Singleton objects');
}
/**
* Renvoie la seule instance si elle est appelée en tant que fonction
*
* @return object
*/
public function __invoke()
{
return static::getInstance();
}
}