<?php
declare(strict_types=1);
/**
* php 技术群:781742505
* 为应用程序中服务的创建和初始化提供一个中心位置。
* 解决的问题,如:可能存在多个地方需要引用服务的实例,在这种情况下,直接创建服务实例的代码会散
* 布到整个程序中,造成一段程序存在多个副本,大大增加维护和排错成本。
*
* Class ServiceLocator
*/
class ServiceLocator
{
/**
* @var array
*/
private $services = [];
/**
* @var array
*/
private $instances = [];
/**
* @var array
*/
private $shared = [];
/**
* @param string $class
* @param null $instance
* @param bool $shared
*/
public function addService(
string $class,
$instance = null,
bool $shared = true
) {
$this->services[$class] = $class;
unset($this->instances[$class]);
if ($instance and $shared === true) {
if (!($instance instanceof $class)) {
throw new \InvalidArgumentException("$instance is not an instance of $class");
}
$this->instances[$class] = $instance;
}
$this->shared[$class] = $shared;
}
/**
* @param string $class
*
* @return bool
*/
public function has(string $class): bool
{
return isset($this->services[$class]);
}
/**
* @param string $class
* @param array $args
*
* @return mixed
*/
public function get(string $class, array $args = [])
{
if (!isset($this->instances[$class])) {
try {
$reflector = new \ReflectionClass($class);
} catch (\ReflectionException $e) {
throw new \InvalidArgumentException("Target class [$class] does not exist.");
}
$object = $reflector->newInstanceArgs($args);
if (isset($this->shared[$class]) and $this->shared[$class]) {
$this->instances[$class] = $object;
}
return $object;
}
return $this->instances[$class];
}
}
// Laravel 有对应的实现,就是服务容器。
服务定位器模式
最新推荐文章于 2024-08-14 14:16:50 发布