php容器实现
PHP 容器实现
在 PHP 中,容器(Container)通常指依赖注入容器(Dependency Injection Container),用于管理对象的创建和依赖关系。以下是实现 PHP 容器的几种常见方法:
使用数组实现简单容器
通过数组存储服务定义和实例,实现基本的容器功能。
class Container {
protected $services = [];
public function set($name, callable $definition) {
$this->services[$name] = $definition;
}
public function get($name) {
if (!isset($this->services[$name])) {
throw new Exception("Service not found: {$name}");
}
return $this->services[$name]($this);
}
}
使用反射实现自动依赖注入
通过 PHP 的 Reflection API 自动解析类的依赖关系并实例化对象。
class Container {
protected $instances = [];
public function get($class) {
if (isset($this->instances[$class])) {
return $this->instances[$class];
}
$reflector = new ReflectionClass($class);
$constructor = $reflector->getConstructor();
if (!$constructor) {
return new $class;
}
$parameters = $constructor->getParameters();
$dependencies = [];
foreach ($parameters as $parameter) {
$dependency = $parameter->getClass();
if ($dependency) {
$dependencies[] = $this->get($dependency->name);
} else {
throw new Exception("Cannot resolve dependency: {$parameter->name}");
}
}
$this->instances[$class] = $reflector->newInstanceArgs($dependencies);
return $this->instances[$class];
}
}
使用 PSR-11 标准实现容器
遵循 PSR-11(Container Interface)标准实现容器,提高与其他框架的兼容性。
use Psr\Container\ContainerInterface;
class Container implements ContainerInterface {
protected $services = [];
public function get($id) {
if (!$this->has($id)) {
throw new ContainerException("Service not found: {$id}");
}
return $this->services[$id]($this);
}
public function has($id) {
return isset($this->services[$id]);
}
public function set($id, callable $definition) {
$this->services[$id] = $definition;
}
}
使用现有容器库
直接使用成熟的 PHP 容器库,如 PHP-DI、Laravel 的容器等。
// 使用 PHP-DI
$container = new DI\Container();
$container->set('service', function() {
return new SomeService();
});
$service = $container->get('service');
实现容器的单例模式
确保某些服务在容器中以单例模式存在,避免重复创建。
class Container {
protected $singletons = [];
public function singleton($name, callable $definition) {
$this->singletons[$name] = $definition;
}
public function get($name) {
if (isset($this->singletons[$name])) {
if (!isset($this->instances[$name])) {
$this->instances[$name] = $this->singletons[$name]($this);
}
return $this->instances[$name];
}
throw new Exception("Service not found: {$name}");
}
}
通过以上方法,可以实现不同复杂度的 PHP 容器,满足项目需求。







