功能实现
基于example1的Container实现,添加对基本数据类型以及mixed
变量的实现支持(赋默认值)
代码实现 Container
public function create($abstract)
{
// temporary constraint
static $times = 0;
if (++$times > 100) {
$times = 0;
throw new class('exec too many times in create method.') extends Exception implements ContainerExceptionInterface{ };
}
$refClass = new ReflectionClass($abstract);
if ($refClass->getName() === Closure::class) {
return function (){};
} elseif ($refClass->hasMethod('__construct')) {
$_constructParams = array_map(function (ReflectionParameter $param) {
if ($param->getClass()) {
return $this->create($param->getClass()->getName());
} elseif ($param->isDefaultValueAvailable()) {
return $param->getDefaultValue();
} elseif ($param->getType()) {
return ([
'string' => '',
'int' => 0,
'array' => [],
'bool' => false,
'float' => 0.0,
'iterable' => [],
'callable' => function() {}
])[$param->getType()->getName()] ?? null;
} else {
return null;
}
}, $refClass->getMethod('__construct')->getParameters());
}
return $refClass->newInstance(... ($_constructParams ?? []));
}
- 以下代码主要用于限制方法的最大执行次数,防止相互依赖造成的程序死循环,本例忽略此段代码
// temporary constraint
static $times = 0;
if (++$times > 100) {
$times = 0;
throw new class('exec too many times in create method.') extends Exception implements ContainerExceptionInterface{ };
}
实现思路
- 列出无法以类解析或者无法通过new创建的类(仅考虑PHP内部的类)参数列表的数据类型
string
int
array
bool
float
iterable
callable
Closure
网友评论