2022-01-25 15:35:48 +08:00
|
|
|
<?php
|
2023-04-16 01:45:33 +08:00
|
|
|
declare(strict_types=1);
|
2022-01-25 15:35:48 +08:00
|
|
|
|
|
|
|
|
namespace Kiri\Di;
|
|
|
|
|
|
2022-12-13 14:10:21 +08:00
|
|
|
use Exception;
|
2022-01-25 15:35:48 +08:00
|
|
|
use Kiri;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 服务定位器
|
|
|
|
|
*/
|
2022-02-03 14:54:38 +08:00
|
|
|
class LocalService
|
2022-01-25 15:35:48 +08:00
|
|
|
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private array $_components = [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private array $_definition = [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param $name
|
|
|
|
|
* @param $define
|
|
|
|
|
*/
|
2022-12-13 14:10:21 +08:00
|
|
|
public function set($name, $define): void
|
2022-01-25 15:35:48 +08:00
|
|
|
{
|
|
|
|
|
unset($this->_components[$name]);
|
|
|
|
|
|
|
|
|
|
$this->_definition[$name] = $define;
|
|
|
|
|
if (is_object($define) || $define instanceof \Closure) {
|
|
|
|
|
$this->_components[$name] = $define;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
2022-12-13 14:10:21 +08:00
|
|
|
* @throws Exception
|
2022-01-25 15:35:48 +08:00
|
|
|
*/
|
|
|
|
|
public function get(string $name, $throwException = true)
|
|
|
|
|
{
|
|
|
|
|
if (isset($this->_components[$name])) {
|
|
|
|
|
return $this->_components[$name];
|
|
|
|
|
}
|
|
|
|
|
if (isset($this->_definition[$name])) {
|
|
|
|
|
$definition = $this->_definition[$name];
|
|
|
|
|
if (is_object($definition) && !$definition instanceof \Closure) {
|
|
|
|
|
return $this->_components[$name] = $definition;
|
|
|
|
|
}
|
|
|
|
|
return $this->_components[$name] = Kiri::createObject($definition);
|
|
|
|
|
} else if ($throwException) {
|
2022-12-13 14:10:21 +08:00
|
|
|
throw new Exception("Unknown component ID: $name");
|
2022-01-25 15:35:48 +08:00
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param array $components
|
|
|
|
|
*/
|
2022-12-13 14:10:21 +08:00
|
|
|
public function setComponents(array $components): void
|
2022-01-25 15:35:48 +08:00
|
|
|
{
|
|
|
|
|
foreach ($components as $name => $component) {
|
|
|
|
|
$this->set($name, $component);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param $id
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
|
|
|
|
public function has($id): bool
|
|
|
|
|
{
|
|
|
|
|
return isset($this->_components[$id]) || isset($this->_definition[$id]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param $id
|
|
|
|
|
*/
|
|
|
|
|
public function remove($id): void
|
|
|
|
|
{
|
|
|
|
|
unset($this->_components[$id], $this->_definition[$id]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|