我正在制作自己的练习框架,我坚持使用DI / IoC容器,并在构造函数中发送参数。
Container.php
class Container
{
private $registry = array();
private $shared = array();
public function set($name, Closure $resolve)
{
if (!$this->exists($name)) {
$this->registry[$name] = $resolve;
} else {
throw new Exception('Class with name ' . $name . ' is already registered.');
}
}
public function get($name, $arguments = array())
{
if (!$this->exists($name, 'shared')) {
$this->shared[$name] = $this->getNew($name, $arguments);
}
return $this->shared[$name];
}
public function getNew($name, $arguments = array())
{
if ($this->exists($name, 'registry')) {
$class = $this->registry[$name];
return $class();
}
throw new Exception('Class with name ' . $name . ' does not exist.');
}
private function exists($name, $type = 'registry')
{
return array_key_exists($name, $this->$type);
}
}
用法:
$container = new Container;
$container->set('file', function() {
return new Application\Library\File();
});
$container->set('cache', function($path, $type = 'json') use ($container) {
return new Application\Library\Cache($container->get('file'), $path, $type);
});
$params = array (
'path/to/cache/',
'json'
);
$cache = $container->get('cache', $params);
问题是:我如何使用 get()或 getNew()方法向构造函数发送参数/参数。我看到 ReflectionClass($ classname)和 newInstanceArgs($ args),但我不知道如何使用它以及放置它的位置。
编辑 - 也许是这样的:
public function getNew($name, $arguments = array())
{
if ($this->exists($name, 'registry')) {
if (count($arguments) > 0) {
$object = new ReflectionClass($name);
return $object->newInstanceArgs($arguments);
} else {
$class = $this->registry[$name];
return $class();
}
}
throw new Exception('Class with name ' . $name . ' does not exist.');
}
但它不起作用,因为为了创建缓存类,我只使用 $ container-> get()和$ params数组注入3个参数中的2个。第一个参数在 $ container-> set()中使用文件类修复,并且在实例创建时无法正确注入。有没有解决方案?
错误: 可捕获的致命错误:传递给Application \ Library \ Cache :: __ construct()的参数1必须是Application \ Library \ File的一个实例,给定的字符串
答案 0 :(得分:0)
可行的解决方案有效,但我对它不满意:
public function getNew($name, $arguments = array())
{
if ($this->exists($name, 'registry')) {
$class = $this->registry[$name];
$count = count($arguments);
switch ($count) {
case 1:
$object = $class($arguments[0]);
break;
case 2:
$object = $class($arguments[0], $arguments[1]);
break;
case 3:
$object = $class($arguments[0], $arguments[1], $arguments[2]);
break;
case 4:
$object = $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
break;
default:
$object = $class();
break;
}
return $object;
}
throw new Exception('Class with name ' . $name . ' does not exist.');
}
计算$参数的数量,通过switch case并返回带有注入参数的$ classname实例。