在PHP中,依賴注入(Dependency Injection,簡稱DI)是一種設(shè)計(jì)模式,用于降低代碼之間的耦合度。通過使用反射,我們可以在運(yùn)行時動態(tài)地實(shí)例化和注入依賴。以下是一個簡單的示例,展示了如何使用PHP反射實(shí)現(xiàn)依賴注入:
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
在這個示例中,我們創(chuàng)建了一個簡單的依賴注入容器,它使用反射來動態(tài)地實(shí)例化和注入依賴。resolveDependencies
函數(shù)接受一個容器實(shí)例和一個類型提示數(shù)組,然后使用反射來獲取類的構(gòu)造函數(shù)和依賴項(xiàng)。接下來,它從容器中獲取這些依賴項(xiàng)并使用它們來實(shí)例化類。最后,我們使用這個容器來實(shí)例化一個實(shí)現(xiàn)了MyInterface
接口的類,并調(diào)用其doSomething
方法。