关于PHP的依赖倒置(DependencyInjection)

关于PHP的依赖倒置(DependencyInjection)

内容导读

收集整理的这篇技术教程文章主要介绍了关于PHP的依赖倒置(DependencyInjection),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2080字,纯文字阅读大概需要3分钟

内容图文

这篇文章主要介绍了PHP依赖倒置(Dependency Injection)代码实例本文只提供实现代码,需要的朋友可以参考下

实现类:

<?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 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中文网!

相关推荐:

关于PHP和jQuery 注册模块的开发

关于PHP – EasyUI DataGrid 资料存的方法介绍

以上就是关于PHP的依赖倒置(Dependency Injection)的详细内容,更多请关注Gxl网其它相关文章!

内容总结

以上是为您收集整理的关于PHP的依赖倒置(DependencyInjection)全部内容,希望文章能够帮你解决关于PHP的依赖倒置(DependencyInjection)所遇到的程序开发问题。 如果觉得技术教程内容还不错,欢迎将网站推荐给程序员好友。

内容备注

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。


本文关键词:

联系我们

在线咨询:点击这里给我发消息

邮件:w420220301@qq.com