I am getting my head around DI
and IoC
; using Pimple for now. Lets say I have my IoC defined early in the execution flow
$container = new Injection\Container();
$container['config'] = function ($c) {
return new Config($c['loader']);
};
$container['request'] = function ($c) {
return new Request($c['config']);
};
...
And a router class that call_user_func_array
//$class = 'Dog', $method = 'woof', $this->args = ['foo', 'bar']
call_user_func_array(array(new $class, $method), $this->args);
So new object is instantiated without being aware of the IoC
but still I would like to reuse some of the services defined.
class Dog
{
public function woof($var1, $var2)
{
//$request = IoC service here
}
}
My question is:
- What would be the proper way to pass the
IoC
to the class (static seems to be evil...) or - Is it even necessary to pass the container around and other methods/concepts exist?
Read some nice articles, however was not able to figure it out
Update
The evil way I did that was defining another service that saves the IoC
in a static property
$container['services'] = function ($c) {
return Services::create($c); //make the service
};
$container['services']; //call the service
and access it later in the
class Dog
{
public function woof($var1, $var2)
{
$services = new Services();
$request = $services['request']; //retrieving the request service
}
}
Update 2
Decided to use the least harmful way
//passing the container here
call_user_func_array(array(new $class($container), $method), $this->args);
And store the parameter in __constructor
public $container;
public function __construct(Injection\Container $container)
{
$this->container = $container;
}