/
example.php
112 lines (95 loc) · 1.81 KB
/
example.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
* Box Lib
*/
require 'box.php';
/**
* Class Product
*/
class Product
{
public $name = 'Test Product';
}
/**
* Interface ProductRepositoryInterface
*/
interface ProductRepositoryInterface
{
public function getName();
}
/**
* Class ProductRepository
*/
class ProductRepository implements ProductRepositoryInterface
{
public function __construct(Product $product)
{
$this->product = $product;
}
public function getName()
{
return $this->product->name;
}
}
/**
* Class ProductController
*/
class ProductController
{
protected $repository;
public function __construct(ProductRepositoryInterface $repository)
{
$this->repository = $repository;
}
public function getName()
{
return $this->repository->getName();
}
}
/**
* Initialize a new Box
*/
$box = new Box;
/**
* Bind Product to the container
*/
$box->bind('Product', function ()
{
return new Product;
});
/**
* Bind Repository to the container
*/
$box->bind('ProductRepositoryInterface', function () use ($box)
{
return new ProductRepository($box->make('Product'));
});
/**
* Create new Reflection Class for the ProductController
*/
$class = new ReflectionClass('ProductController');
/**
* Get the constructor
*/
$constructor = $class->getConstructor();
/**
* Check with parameter the constructor needs
*/
$parameters = $constructor->getParameters();
$arguments = [];
/**
* Get the objects from the box by parameter name
*/
foreach($parameters as $parameter)
{
$arguments[] = $box->make(strval($parameter->getClass()->getName()));
}
/**
* Create a new instance of the controller with the arguments that
* where taken from the box
*/
$controller = $class->newInstanceArgs($arguments);
/**
* Fire a test method
*/
echo $controller->getName()."\n";