-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDIContainer.php
More file actions
91 lines (77 loc) · 2.86 KB
/
Copy pathDIContainer.php
File metadata and controls
91 lines (77 loc) · 2.86 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
<?php
namespace core;
use ArrayAccess;
use core\exceptions\FactoryAlreadyExists, core\exceptions\ValueError;
use ReflectionClass;
/*
* DI контейнер, или контейнер зависимостей
* Хранит массив фабрик и готовых объектов
* Выдаёт зависимости, создавая нужные объекты или получая их из кэша
* Разрешает все зависимости класса через получение типов аргументов консттруктора и поиска их в контейнере
* Реализует интерфейс массива
*/
class DIContainer implements ArrayAccess {
private array $factories = [];
private array $objects = [];
public function register(string $name, string | callable $factory): void
{
if (!isset($this->factories[$name])) {
$this->factories[$name] = $factory;
} else {
throw new FactoryAlreadyExists();
}
}
private function resolve_dependencies(string $class): object
{
if (!class_exists($class)) {
throw new ValueError();
}
$classReflector = new ReflectionClass($class);
$constructReflector = $classReflector->getConstructor();
if (empty($constructReflector)) {
return new $class;
}
$constructArguments = $constructReflector->getParameters();
if (empty($constructArguments)) {
return new $class;
}
$args = [];
foreach ($constructArguments as $argument) {
$argumentType = $argument->getType()->getName();
$args[$argument->getName()] = $this->get($argumentType);
}
return new $class(...$args);
}
public function get(string $name)
{
if (isset($this->objects[$name])) {
return $this->objects[$name];
} else {
// var_dump($this->factories);
if (is_callable($this->factories[$name])) {
$obj = $this->factories[$name]($this);
} else if (class_exists($this->factories[$name])) {
$obj = $this->resolve_dependencies($this->factories[$name]);
}
$this->objects[$name] = $obj;
return $obj;
}
}
public function offsetSet($offset, $value): void {
if (!is_callable($value) and !class_exists($value)) {
echo $value;
throw new ValueError();
}
$this->register($offset, $value);
}
public function offsetExists($offset): bool {
return isset($this->factories[$offset]);
}
public function offsetUnset($offset): void {
unset($this->factories[$offset]);
unset($this->objects[$offset]);
}
public function offsetGet($offset): mixed {
return $this->get($offset);
}
}