-
Notifications
You must be signed in to change notification settings - Fork 0
/
IoC.php
72 lines (59 loc) · 1.96 KB
/
IoC.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
<?php namespace Devtools;
use ReflectionClass;
use Closure;
abstract class IoC
{
protected static $objectDefinitions = array();
protected static $registryOfCreatedObjects = array();
public static function bind($objectName, Closure $callable)
{
self::$objectDefinitions[$objectName] = $callable;
return true;
}
public static function make($objectName, $singleton = true)
{
if ($singleton && self::isInstantiated($objectName)) {
return self::$registryOfCreatedObjects[$objectName];
}
if (self::isRegistered($objectName)) {
return self::makeWithBinding($objectName);
}
if (self::objectRegistersBinding($objectName)) {
$objectName::register();
return self::make($objectName, $singleton);
}
return self::makeWithReflection($objectName);
}
private static function isInstantiated($objectName)
{
return isset(self::$registryOfCreatedObjects[$objectName]);
}
private static function isRegistered($objectName)
{
return isset(self::$objectDefinitions[$objectName]);
}
private static function makeWithBinding($objectName)
{
$func = self::$objectDefinitions[$objectName];
return self::$registryOfCreatedObjects[$objectName] = $func();
}
private static function objectRegistersBinding($objectName)
{
return method_exists($objectName, 'register');
}
private static function makeWithReflection($objectName)
{
$reflection = new ReflectionClass($objectName);
$dependencies = $reflection->getMethod('__construct')->getParameters();
$params = array();
foreach ($dependencies as $dependency) {
array_push(
$params,
self::make(
$dependency->getClass()->getName()
)
);
}
return $reflection->newInstanceArgs($params);
}
}