在PHP中,依賴注入(Dependency Injection,簡稱DI)是一種設計模式,用于降低代碼之間的耦合度。通過使用反射,我們可以在運行時動態地實例化和注入依賴。以下是一個簡單的示例,展示了如何使用PHP反射實現依賴注入:
interface MyInterface
{
public function doSomething();
}
class MyImplementationA implements MyInterface
{
public function doSomething()
{
echo "MyImplementationA doSomething\n";
}
}
class MyImplementationB implements MyInterface
{
public function doSomething()
{
echo "MyImplementationB doSomething\n";
}
}
class Container
{
private $instances = [];
public function set($key, $instance)
{
if (!is_object($instance)) {
throw new InvalidArgumentException('Instance must be an object');
}
$this->instances[$key] = $instance;
}
public function get($key)
{
if (!isset($this->instances[$key])) {
throw new InvalidArgumentException('No instance found for key: ' . $key);
}
return $this->instances[$key];
}
}
function resolveDependencies(Container $container, array $typeHints)
{
$reflection = new ReflectionClass($typeHints['class']);
$constructor = $reflection->getConstructor();
if ($constructor === null) {
throw new InvalidArgumentException('Class ' . $typeHints['class'] . ' has no constructor');
}
$dependencies = [];
foreach ($constructor->getParameters() as $parameter) {
$dependencyName = $parameter->getName();
if (!isset($container->get($dependencyName))) {
throw new InvalidArgumentException('Dependency ' . $dependencyName . ' not found');
}
$dependencies[] = $container->get($dependencyName);
}
return $reflection->newInstanceArgs($dependencies);
}
$container = new Container();
$container->set('myInterface', resolveDependencies($container, [
'class' => MyInterface::class,
'dependencies' => [MyImplementationA::class, MyImplementationB::class],
]));
$instance = $container->get('myInterface');
$instance->doSomething(); // Output: MyImplementationA doSomething
在這個示例中,我們創建了一個簡單的依賴注入容器,它使用反射來動態地實例化和注入依賴。resolveDependencies
函數接受一個容器實例和一個類型提示數組,然后使用反射來獲取類的構造函數和依賴項。接下來,它從容器中獲取這些依賴項并使用它們來實例化類。最后,我們使用這個容器來實例化一個實現了MyInterface
接口的類,并調用其doSomething
方法。