Yii2 依赖注入
2019-08-25 22:22:29 7 举报
AI智能生成
Yii2 依赖注入
作者其他创作
大纲/内容
yii\\di\\Container
private $_singletons = [];
private $_definitions = [];
private $_params = [];
private $_reflections = [];
private $_dependencies = [];
$this->_params[$class] = $params;
unset($this->_singletons[$class]);
$this->_singletons[$class] = null;
if (empty($definition))
return ['class' => $class];
elseif (is_string($definition))
return ['class' => $definition];
return $definition;
elseif (is_array($definition))
if (!isset($definition['class']))
$definition['class'] = $class;
setDefinitions(array $definitions)
foreach ($definitions as $class => $definition)
if (count($definition) === 2 && array_values($definition) === $definition)
continue;
setSingletons(array $singletons)
foreach ($singletons as $class => $definition)
if (is_callable($callback))
else
if (is_array($callback))
$reflection = new \\ReflectionFunction($callback);
$args = [];
$associative = ArrayHelper::isAssociative($params);
foreach ($reflection->getParameters() as $param)
foreach ($params as $value)
$args[] = $value;
return $args;
if (empty($this->_params[$class]))
return $params;
elseif (empty($params))
return $this->_params[$class];
$ps = $this->_params[$class];
foreach ($params as $index => $value)
$ps[$index] = $value;
return $ps;
if (isset($this->_singletons[$class]))
return $this->_singletons[$class];
elseif (!isset($this->_definitions[$class]))
$definition = $this->_definitions[$class];
$concrete = $definition['class'];
unset($definition['class']);
if ($concrete === $class)
elseif (is_object($definition))
return $this->_singletons[$class] = $definition;
$this->_singletons[$class] = $object;
return $object;
foreach ($params as $index => $param)
$dependencies[$index] = $param;
if (empty($config))
return $reflection->newInstanceArgs($dependencies);
if (!empty($dependencies) && $reflection->implementsInterface('yii\\base\\Configurable'))
$dependencies[count($dependencies) - 1] = $config;
$object = $reflection->newInstanceArgs($dependencies);
foreach ($config as $name => $value)
$object->$name = $value;
protected getDependencies($class)
if (isset($this->_reflections[$class]))
$dependencies = [];
$reflection = new ReflectionClass($class);
$constructor = $reflection->getConstructor();
if ($constructor !== null)
foreach ($constructor->getParameters() as $param)
if ($param->isDefaultValueAvailable())
$dependencies[] = $param->getDefaultValue();
$c = $param->getClass();
$dependencies[] = Instance::of($c === null ? null : $c->getName());
$this->_reflections[$class] = $reflection;
$this->_dependencies[$class] = $dependencies;
foreach ($dependencies as $index => $dependency)
if ($dependency instanceof Instance)
if ($dependency->id !== null)
$dependencies[$index] = $this->get($dependency->id);
return $dependencies;
has($class)
return isset($this->_definitions[$class]);
clear($class)
getDefinitions()
return $this->_definitions;
0 条评论
回复 删除
下一页