25
25
26
26
namespace doganoo \PHPUtil \DI ;
27
27
28
+ use doganoo \PHPAlgorithms \Datastructure \Lists \Node ;
29
+ use doganoo \PHPAlgorithms \Datastructure \Maps \HashMap ;
28
30
use doganoo \PHPUtil \Exception \ClassNotFoundException ;
29
- use doganoo \ PHPUtil \ Util \ AppContainer ;
31
+ use Exception ;
30
32
use ReflectionClass ;
31
33
use ReflectionParameter ;
32
34
47
49
*/
48
50
class Container {
49
51
52
+ private $ instances = null ;
53
+
54
+ private $ created = null ;
55
+
56
+ public function __construct () {
57
+ $ this ->instances = new HashMap ();
58
+ $ this ->created = new HashMap ();
59
+ }
60
+
61
+ public function add (string $ name , callable $ callable ):void {
62
+ $ this ->instances ->add ($ name , $ callable );
63
+ }
50
64
/**
51
65
* retrieving the container instance.
52
66
*
@@ -56,25 +70,47 @@ class Container {
56
70
* @return mixed|null
57
71
*/
58
72
public function get (string $ name , ...$ params ) {
59
- try {
73
+ if ($ this ->created ->containsKey ($ name )) return $ this ->created ->getNodeByKey ($ name )->getValue ();
74
+ if ($ this ->instances ->containsKey ($ name )) return $ this ->fromInstances ($ name , $ params );
75
+
76
+ try {
60
77
$ reflectionClass = new ReflectionClass ($ name );
61
78
$ constructor = $ reflectionClass ->getConstructor ();
62
79
$ parameters = [];
63
80
64
- if (null !== $ constructor ){
81
+ if (null !== $ constructor ) {
65
82
/** @var ReflectionParameter $parameter */
66
- foreach ($ constructor ->getParameters () as $ parameter ){
83
+ foreach ($ constructor ->getParameters () as $ parameter ) {
67
84
$ className = $ parameter ->getClass ()->getName ();
68
- $ class = AppContainer:: get ($ className );
85
+ $ class = $ this -> get ($ className );
69
86
if (null === $ class ) throw new ClassNotFoundException ();
70
87
$ parameters [] = $ class ;
71
88
}
72
89
}
73
90
$ clazz = $ reflectionClass ->newInstanceArgs ($ parameters + $ params );
91
+ $ this ->created ->add ($ name , $ clazz );
74
92
return $ clazz ;
75
- } catch (ClassNotFoundException $ exception ){
93
+ } catch (Exception $ exception ) {
94
+ return null ;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * @param string $name
100
+ * @param mixed ...$params
101
+ * @return mixed|null
102
+ */
103
+ private function fromInstances (string $ name , ...$ params ){
104
+ if (false === $ this ->instances ->containsKey ($ name )) return null ;
105
+
106
+ /** @var Node $node */
107
+ $ node = $ this ->instances ->getNodeByKey ($ name );
108
+ if (null === $ node ) {
76
109
return null ;
77
110
}
111
+ $ clazz = $ node ->getValue ()($ params );
112
+ $ this ->created ->add ($ name , $ clazz );
113
+ return $ clazz ;
78
114
}
79
115
80
116
}
0 commit comments