PHP依賴倒置(Dependency Injection)代碼實例
更新時間:2014年10月11日 12:08:16 作者:十年燈
這篇文章主要介紹了PHP依賴倒置(Dependency Injection)代碼實例本文只提供實現(xiàn)代碼,需要的朋友可以參考下
實現(xiàn)類:
復(fù)制代碼 代碼如下:
<?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;
}
}
實現(xiàn)實例:
復(fù)制代碼 代碼如下:
<?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);
您可能感興趣的文章:
相關(guān)文章
PHP微信開發(fā)之微信消息自動回復(fù)下所遇到的坑
這篇文章是小編給大家介紹的微信消息自動回復(fù)下所遇到的坑的相關(guān)內(nèi)容,在日常項目開發(fā)中經(jīng)常遇到,非常具有參考借鑒價值,感興趣的小伙伴一起學(xué)習(xí)吧2016-05-05php的sprintf函數(shù)的用法 控制浮點數(shù)格式
這篇文章主要介紹了php的sprintf函數(shù)的用法,需要的朋友可以參考下2014-02-02PHP面向?qū)ο笾I(lǐng)域模型+數(shù)據(jù)映射器實例(分析)
下面小編就為大家?guī)硪黄狿HP面向?qū)ο笾I(lǐng)域模型+數(shù)據(jù)映射器實例(分析)。小編覺得挺不錯的?,F(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06laravel框架之?dāng)?shù)據(jù)庫查出來的對象實現(xiàn)轉(zhuǎn)化為數(shù)組
今天小編就為大家分享一篇laravel框架之?dāng)?shù)據(jù)庫查出來的對象實現(xiàn)轉(zhuǎn)化為數(shù)組,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10