PHP依赖倒置(Dependency Injection)代码实例
实现类:
<?php classContainer { protected$setings=array(); publicfunctionset($abstract,$concrete=null) { if($concrete===null){ $concrete=$abstract; } $this->setings[$abstract]=$concrete; } publicfunctionget($abstract,$parameters=array()) { if(!isset($this->setings[$abstract])){ returnnull; } return$this->build($this->setings[$abstract],$parameters); } publicfunctionbuild($concrete,$parameters) { if($concreteinstanceofClosure){ return$concrete($this,$parameters); } $reflector=newReflectionClass($concrete); if(!$reflector->isInstantiable()){ thrownewException("Class{$concrete}isnotinstantiable"); } $constructor=$reflector->getConstructor(); if(is_null($constructor)){ return$reflector->newInstance(); } $parameters=$constructor->getParameters(); $dependencies=$this->getDependencies($parameters); return$reflector->newInstanceArgs($dependencies); } publicfunctiongetDependencies($parameters) { $dependencies=array(); foreach($parametersas$parameter){ $dependency=$parameter->getClass(); if($dependency===null){ if($parameter->isDefaultValueAvailable()){ $dependencies[]=$parameter->getDefaultValue(); }else{ thrownewException("Cannotberesolveclassdependency{$parameter->name}"); } }else{ $dependencies[]=$this->get($dependency->name); } } return$dependencies; } }
实现实例:
<?php require'container.php'; interfaceMyInterface{} classFooimplementsMyInterface{} classBarimplementsMyInterface{} classBaz { publicfunction__construct(MyInterface$foo) { $this->foo=$foo; } } $container=newContainer(); $container->set('Baz','Baz'); $container->set('MyInterface','Foo'); $baz=$container->get('Baz'); print_r($baz); $container->set('MyInterface','Bar'); $baz=$container->get('Baz'); print_r($baz);