This commit is contained in:
2021-11-04 17:34:20 +08:00
parent a435df8453
commit 320a01d822
+57 -55
View File
@@ -13,74 +13,76 @@ class LocalService extends Component
{ {
private array $_components = []; private array $_components = [];
private array $_definition = []; private array $_definition = [];
/** /**
* @param $name * @param $name
* @param $define * @param $define
*/ */
public function set($name, $define) public function set($name, $define)
{ {
unset($this->_components[$name]); unset($this->_components[$name]);
$this->_definition[$name] = $define; $this->_definition[$name] = $define;
$this->_components[$name] = $define; if (is_object($define) || $define instanceof \Closure) {
} $this->_components[$name] = $define;
}
}
/** /**
* @throws \Exception * @throws \Exception
*/ */
public function get(string $name, $throwException = true) public function get(string $name, $throwException = true)
{ {
if (isset($this->_components[$name])) { if (isset($this->_components[$name])) {
return $this->_components[$name]; return $this->_components[$name];
} }
if (isset($this->_definition[$name])) { if (isset($this->_definition[$name])) {
$definition = $this->_definition[$name]; $definition = $this->_definition[$name];
if (is_object($definition) && !$definition instanceof \Closure) { if (is_object($definition) && !$definition instanceof \Closure) {
return $this->_components[$name] = $definition; return $this->_components[$name] = $definition;
} }
return $this->_components[$name] = Kiri::createObject($definition); return $this->_components[$name] = Kiri::createObject($definition);
} else if ($throwException) { } else if ($throwException) {
throw new \Exception("Unknown component ID: $name"); throw new \Exception("Unknown component ID: $name");
} }
return null; return null;
} }
/** /**
* @param array $components * @param array $components
*/ */
public function setComponents(array $components) public function setComponents(array $components)
{ {
foreach ($components as $name => $component) { foreach ($components as $name => $component) {
$this->set($name, $component); $this->set($name, $component);
} }
} }
/** /**
* @param $id * @param $id
* @return bool * @return bool
*/ */
public function has($id): bool public function has($id): bool
{ {
return isset($this->_components[$id]) || isset($this->_definition[$id]); return isset($this->_components[$id]) || isset($this->_definition[$id]);
} }
/** /**
* @param $id * @param $id
*/ */
public function remove($id): void public function remove($id): void
{ {
unset($this->_components[$id], $this->_definition[$id]); unset($this->_components[$id], $this->_definition[$id]);
} }
} }