-
Notifications
You must be signed in to change notification settings - Fork 1
/
Amslib_Container.php
93 lines (79 loc) · 2.9 KB
/
Amslib_Container.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
88
89
90
91
92
93
<?php
/**
* A Dependency Locator for managing injection and configuration of resources
*
* User: Chris Thomas
* Date: 10/11/2015
* Time: 12:03
*
* notes:
* - This is my first attempt at a dependency container
* - I'm trying to write this without referencing another container, to explore whether I fully understand the idea
* - I haven't figured out how I'm going to allow targets to require dependencies yet
*/
class Amslib_Container implements ArrayAccess
{
protected $list;
protected function process($object, $dependencies = [])
{
if($object instanceof Closure){
return $object($this, $dependencies);
}else if(is_callable($object)){
return call_user_func_array($object,[$this,$dependencies]);
}else if(is_string($object) && class_exists($object) && class_exists("ReflectionClass")){
$rc = new ReflectionClass($object);
return $rc->newInstanceArgs([$this,$dependencies]);
}else if(is_string($object) && !empty($this[$object])){
return $this[$object];
}else{
throw new \InvalidArgumentException("\$object parameter was not recognised type [closure, callable, string]");
}
}
public function __construct()
{
$this->list = [];
}
public function create($name, $target, array $dependencies = [])
{
if(!is_string($name) || empty($name)){
throw new InvalidArgumentException("the \$name parameter was not valid [name = '".Amslib_Debug::vdump($name)."']");
}
$this[$name] = $this->process($target, $dependencies);
}
public function factory($name, $target, array $dependencies = [])
{
$closure = function() use ($target, $dependencies) {
// NOTE: I would prefer to acquire each dependency here, instead of inside the callback
return $this->process($target, $dependencies);
};
// create a factory method which creates on demand a new dependency
$this[$name] = $closure->bindTo($this);
}
public function remove($name)
{
unset($this[$name]);
}
public function offsetSet($name,$value)
{
// set one of the dependencies
$this->list[$name] = $value;
}
public function offsetGet($name)
{
if(!is_string($name) || empty($name)){
throw new InvalidArgumentException("the \$name parameter was not valid [name = '".Amslib_Debug::vdump($name)."']");
}
$target = $this->list[$name];
return $target instanceof Closure ? $target() : $target;
}
public function offsetUnset($name)
{
unset($this->list[$name]);
}
public function offsetExists($name)
{
if(!array_key_exists($name,$this->list)){
throw new InvalidArgumentException("the \$name parameter does not exist in container [name = '".Admin_Debug::vdump($name)."']");
}
}
}