ServiceLocator类继承Component类。
一、属性
1. $_components 组件实例数组
2. $_definitions 组件定义数组
// 组件实例
private $_components = [];
//组件定义
private $_definitions = [];
二、方法
1. __get方法,获取$name对应的值
// 获取$name对应的值
public function __get($name)
{
if ($this->has($name)) {
return $this->get($name);
}
return parent::__get($name);
}
2. __isset方法,检查$name是否存在
/**
* 检查$name是否存在
*/
public function __isset($name)
{
if ($this->has($name)) {
return true;
}
return parent::__isset($name);
}
3. has方法,检查是否存在组件实例或定义
//检查是否存在组件实例或定义
public function has($id, $checkInstance = false)
{
return $checkInstance ?
isset($this->_components[$id]) :
isset($this->_definitions[$id]);
}
4. get方法,根据id返回组件
/**
* 根据id返回对应的组件实例
*/
public function get($id, $throwException = true)
{
if (isset($this->_components[$id])) {
return $this->_components[$id];
}
if (isset($this->_definitions[$id])) {
$definition = $this->_definitions[$id];
if (is_object($definition) && !$definition instanceof Closure) {
return $this->_components[$id] = $definition;
}
return $this->_components[$id] = Yii::createObject($definition);
} elseif ($throwException) {
throw new InvalidConfigException("Unknown component ID: $id");
}
return null;
}
5. set方法,注册组件
// 注册组件
public function set($id, $definition)
{
unset($this->_components[$id]);
if ($definition === null) {
unset($this->_definitions[$id]);
return;
}
if (is_object($definition) || is_callable($definition, true)) {
// an object, a class name, or a PHP callable
$this->_definitions[$id] = $definition;
} elseif (is_array($definition)) {
// a configuration array
if (isset($definition['__class'])) {
$this->_definitions[$id] = $definition;
$this->_definitions[$id]['class'] = $definition['__class'];
unset($this->_definitions[$id]['__class']);
} elseif (isset($definition['class'])) {
$this->_definitions[$id] = $definition;
} else {
throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
}
} else {
throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
}
}
6. clear方法,移除组件
// 移除指定组件
public function clear($id)
{
unset(
$this->_definitions[$id],
$this->_components[$id]
);
}
7. getComponents方法,返回组件实例或定义列表
//返回组件定义或已加载的组件实例的列表。
public function getComponents($returnDefinitions = true)
{
return $returnDefinitions ?
$this->_definitions :
$this->_components;
}
8. setComponents方法,注册组件
//注册组件
public function setComponents($components)
{
foreach ($components as $id => $component) {
$this->set($id, $component);
}
}
总结:
阅读了2个属性和8个方法:
- $_components 组件实例数组
- $_definitions 组件定义数组
- __get方法,获取$name对应的值
- __isset方法,检查$name是否存在
- has方法,检查是否存在组件实例或定义
- get方法,根据id返回组件
- set方法,注册组件
- clear方法,移除组件
- getComponents方法,返回组件实例或定义列表
- setComponents方法,注册组件