DI Container
NghiaNV 7/8/2021
# Description:
- Quản lí và thực hiện binding, resolving các dependency.
- Tự động inject các dependency được type hinting trong application.
# Binding:
abstract class AbstractContainer implements ContainerInterface
{
protected array $instances = [];
public function bind($abstract, $concrete = null): void
{
if ($concrete === null) {
$concrete = $abstract;
}
$this->instances[$abstract] = $concrete;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
Property instances
lưu các dependency được binding trong container.
# Resolve:
public function make($abstract, array $parameters = [])
{
return $this->resolve($this->instances[$abstract], $parameters);
}
1
2
3
4
2
3
4
Get dependency đã được bind trong container.
# Tự động Inject các dependency:
public function resolve($concrete, array $parameters)
{
if ($concrete instanceof Closure) {
return $concrete($this, $parameters);
}
$reflector = new ReflectionClass($concrete);
// check if class is instantiable
if (!$reflector->isInstantiable()) {
throw new Exception("Class {$concrete} is not instantiable");
}
// get class constructor
$constructor = $reflector->getConstructor();
if (is_null($constructor)) {
// get new instance from class
return $reflector->newInstance();
}
// get constructor params
$parameters = $constructor->getParameters();
$dependencies = $this->getDependencies($parameters);
// get new instance with dependencies resolved
return $reflector->newInstanceArgs($dependencies);
}
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
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
Sử dụng Reflection Class để phân tích class và tự động inject các dependency.
Packagist: https://packagist.org/packages/nin/nin (opens new window)