依賴注入 是現代 PHP 開發的核心模式,透過容器管理類別相依性,實現鬆耦合與可測試性。本文提供一個精簡的 DI 容器實作,展示如何以反射自動解析建構子相依、支援介面綁定與閉包工廠。
檔案 container.php:
<?php
class Container
{
protected $bindings = [];
public function set($abstract, $concrete = null)
{
if ($concrete === null) {
$concrete = $abstract;
}
$this->bindings[$abstract] = $concrete;
}
public function get($abstract, $parameters = [])
{
if (!isset($this->bindings[$abstract])) {
return null;
}
return $this->build($this->bindings[$abstract], $parameters);
}
protected function build($concrete, $parameters)
{
if ($concrete instanceof Closure) {
return $concrete($this, $parameters);
}
$reflector = new ReflectionClass($concrete);
if (!$reflector->isInstantiable()) {
throw new Exception("Class {$concrete} is not instantiable");
}
$constructor = $reflector->getConstructor();
if (is_null($constructor)) {
return $reflector->newInstance();
}
$dependencies = $this->getDependencies($constructor->getParameters());
return $reflector->newInstanceArgs($dependencies);
}
protected function getDependencies($parameters)
{
$dependencies = [];
foreach ($parameters as $parameter) {
$dependency = $parameter->getClass();
if ($dependency === null) {
if ($parameter->isDefaultValueAvailable()) {
$dependencies[] = $parameter->getDefaultValue();
} else {
throw new Exception("Cannot resolve class dependency {$parameter->name}");
}
} else {
$dependencies[] = $this->get($dependency->name);
}
}
return $dependencies;
}
}
<?php
require 'container.php';
interface MyInterface {}
class Foo implements MyInterface {}
class Bar implements MyInterface {}
class Baz
{
public function __construct(MyInterface $foo)
{
$this->foo = $foo;
}
}
$container = new Container();
$container->set('Baz', 'Baz');
$container->set('MyInterface', 'Foo');
$baz = $container->get('Baz');
print_r($baz); // Baz 內部注入 Foo 實例
$container->set('MyInterface', 'Bar');
$baz = $container->get('Baz');
print_r($baz); // 同一 Baz 類別,現注入 Bar 實例
這個精簡容器展示了 DI 核心機制:綁定宣告 → 反射分析 → 遞迴解析 → 實例化。雖功能輕量,但已足以支援介面導向設計與單元測試的相依替換。實際專案建議採用成熟套件(如 PHP-DI、Laravel Container、Symfony DependencyInjection)以獲得效能優化、PSR-11 相容與豐富生態。