PHP依赖倒置(Dependency Injection)代码实例
发布:smiling 来源: PHP粉丝网 添加日期:2021-04-16 11:12:42 浏览: 评论:0
这篇文章主要介绍了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}");
- } //www.phpfensi.com
- } 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);
Tags: PHP依赖倒置
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)