《PHP實戰(zhàn):PHP依賴倒置(Dependency Injection)代碼實例》要點:
本文介紹了PHP實戰(zhàn):PHP依賴倒置(Dependency Injection)代碼實例,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP進(jìn)修實現(xiàn)類:
代碼如下:
<?php
?
class Container
{
??? protected $setings = array();
?
??? public function set($abstract, $concrete = null)
??? {
??????? if ($concrete === null) {
??????????? $concrete = $abstract;
??????? }
?
??????? $this->setings[$abstract] = $concrete;
??? }
?
??? public function get($abstract, $parameters = array())
??? {
??????? if (!isset($this->setings[$abstract])) {
??????????? return null;
??????? }
?
??????? return $this->build($this->setings[$abstract], $parameters);
??? }
?
??? public 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();
??????? }
?
??????? $parameters = $constructor->getParameters();
??????? $dependencies = $this->getDependencies($parameters);
?
??????? return $reflector->newInstanceArgs($dependencies);
??? }
?
??? public function getDependencies($parameters)
??? {
??????? $dependencies = array();
??????? foreach ($parameters as $parameter) {
??????????? $dependency = $parameter->getClass();
??????????? if ($dependency === null) {
??????????????? if ($parameter->isDefaultValueAvailable()) {
??????????????????? $dependencies[] = $parameter->getDefaultValue();
??????????????? } else {
??????????????????? throw new Exception("Can not be resolve class dependency {$parameter->name}");
??????????????? }
??????????? } else {
??????????????? $dependencies[] = $this->get($dependency->name);
??????????? }
??????? }
?
??????? return $dependencies;
??? }
}
PHP學(xué)習(xí)實實際例:
代碼如下:
<必修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);
$container->set('MyInterface', 'Bar');
$baz = $container->get('Baz');
print_r($baz);
《PHP實戰(zhàn):PHP依賴倒置(Dependency Injection)代碼實例》是否對您有啟發(fā),歡迎查看更多與《PHP實戰(zhàn):PHP依賴倒置(Dependency Injection)代碼實例》相關(guān)教程,學(xué)精學(xué)透。維易PHP學(xué)院為您提供精彩教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/14566.html