Files
kiri-container/LocalService.php
T

93 lines
1.6 KiB
PHP
Raw Normal View History

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;
2023-11-16 23:50:06 +08:00
use Closure;
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 = [];
2023-11-16 23:50:06 +08:00
/**
* @param $name
* @param $define
* @throws Exception
*/
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;
2023-11-16 23:50:06 +08:00
if (is_object($define) || $define instanceof Closure) {
$this->_components[$name] = $this->get($name, $define);
2022-01-25 15:35:48 +08:00
}
}
/**
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];
2023-11-16 23:50:06 +08:00
if (is_object($definition) && !$definition instanceof Closure) {
2022-01-25 15:35:48 +08:00
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;
}
2023-11-16 23:50:06 +08:00
/**
* @param array $components
* @throws Exception
*/
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]);
}
}