当前位置:Gxlcms > PHP教程 > 关于PHP的依赖倒置(DependencyInjection)

关于PHP的依赖倒置(DependencyInjection)

时间:2021-07-01 10:21:17 帮助过:12人阅读

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

实现类:

  1. <?php
  2. class Container
  3. {
  4. protected $setings = array();
  5. public function set($abstract, $concrete = null)
  6. {
  7. if ($concrete === null) {
  8. $concrete = $abstract;
  9. }
  10. $this->setings[$abstract] = $concrete;
  11. }
  12. public function get($abstract, $parameters = array())
  13. {
  14. if (!isset($this->setings[$abstract])) {
  15. return null;
  16. }
  17. return $this->build($this->setings[$abstract], $parameters);
  18. }
  19. public function build($concrete, $parameters)
  20. {
  21. if ($concrete instanceof Closure) {
  22. return $concrete($this, $parameters);
  23. }
  24. $reflector = new ReflectionClass($concrete);
  25. if (!$reflector->isInstantiable()) {
  26. throw new Exception("Class {$concrete} is not instantiable");
  27. }
  28. $constructor = $reflector->getConstructor();
  29. if (is_null($constructor)) {
  30. return $reflector->newInstance();
  31. }
  32. $parameters = $constructor->getParameters();
  33. $dependencies = $this->getDependencies($parameters);
  34. return $reflector->newInstanceArgs($dependencies);
  35. }
  36. public function getDependencies($parameters)
  37. {
  38. $dependencies = array();
  39. foreach ($parameters as $parameter) {
  40. $dependency = $parameter->getClass();
  41. if ($dependency === null) {
  42. if ($parameter->isDefaultValueAvailable()) {
  43. $dependencies[] = $parameter->getDefaultValue();
  44. } else {
  45. throw new Exception("Can not be resolve class dependency {$parameter->name}");
  46. }
  47. } else {
  48. $dependencies[] = $this->get($dependency->name);
  49. }
  50. }
  51. return $dependencies;
  52. }
  53. }

实现实例:

  1. <?php
  2. require 'container.php';
  3. interface MyInterface{}
  4. class Foo implements MyInterface{}
  5. class Bar implements MyInterface{}
  6. class Baz
  7. {
  8. public function __construct(MyInterface $foo)
  9. {
  10. $this->foo = $foo;
  11. }
  12. }
  13. $container = new Container();
  14. $container->set('Baz', 'Baz');
  15. $container->set('MyInterface', 'Foo');
  16. $baz = $container->get('Baz');
  17. print_r($baz);
  18. $container->set('MyInterface', 'Bar');
  19. $baz = $container->get('Baz');
  20. print_r($baz);

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

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

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

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

人气教程排行