当前位置: 移动技术网 > IT编程>开发语言>PHP > 浅析PHP类的反射来实现依赖注入过程

浅析PHP类的反射来实现依赖注入过程

2018年02月10日  | 移动技术网IT编程  | 我要评论

php具有完整的反射 api,提供了对类、接口、函数、方法和扩展进行逆向工程的能力。通过类的反射提供的能力我们能够知道类是如何被定义的,它有什么属性、什么方法、方法都有哪些参数,类文件的路径是什么等很重要的信息。也正式因为类的反射很多php框架才能实现依赖注入自动解决类与类之间的依赖关系,这给我们平时的开发带来了很大的方便。 本文主要是讲解如何利用类的反射来实现依赖注入(dependency injection),并不会去逐条讲述php reflection里的每一个api,详细的api参考信息请查阅

为了更好地理解,我们通过一个例子来看类的反射,以及如何实现依赖注入。

下面这个类代表了坐标系里的一个点,有两个属性横坐标x和纵坐标y。

/**
 * class point
 */
class point
{
  public $x;
  public $y;

  /**
   * point constructor.
   * @param int $x horizontal value of point's coordinate
   * @param int $y vertical value of point's coordinate
   */
  public function __construct($x = 0, $y = 0)
  {
    $this->x = $x;
    $this->y = $y;
  }
}

接下来这个类代表圆形,可以看到在它的构造函数里有一个参数是point类的,即circle类是依赖与point类的。

class circle
{
  /**
   * @var int
   */
  public $radius;//半径

  /**
   * @var point
   */
  public $center;//圆心点

  const pi = 3.14;

  public function __construct(point $point, $radius = 1)
  {
    $this->center = $point;
    $this->radius = $radius;
  }
  
  //打印圆点的坐标
  public function printcenter()
  {
    printf('center coordinate is (%d, %d)', $this->center->x, $this->center->y);
  }

  //计算圆形的面积
  public function area()
  {
    return 3.14 * pow($this->radius, 2);
  }
}

reflectionclass

下面我们通过反射来对circle这个类进行反向工程。

把circle类的名字传递给reflectionclass来实例化一个reflectionclass类的对象。

$reflectionclass = new reflectionclass(circle::class);
//返回值如下
object(reflectionclass)#1 (1) {
 ["name"]=>
 string(6) "circle"
}

反射出类的常量

$reflectionclass->getconstants();

返回一个由常量名称和值构成的关联数组

array(1) {
 ["pi"]=>
 float(3.14)
}

通过反射获取属性

$reflectionclass->getproperties();

返回一个由reflectionproperty对象构成的数组

array(2) {
 [0]=>
 object(reflectionproperty)#2 (2) {
  ["name"]=>
  string(6) "radius"
  ["class"]=>
  string(6) "circle"
 }
 [1]=>
 object(reflectionproperty)#3 (2) {
  ["name"]=>
  string(6) "center"
  ["class"]=>
  string(6) "circle"
 }
}

反射出类中定义的方法

$reflectionclass->getmethods();

返回reflectionmethod对象构成的数组

array(3) {
 [0]=>
 object(reflectionmethod)#2 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(6) "circle"
 }
 [1]=>
 object(reflectionmethod)#3 (2) {
  ["name"]=>
  string(11) "printcenter"
  ["class"]=>
  string(6) "circle"
 }
 [2]=>
 object(reflectionmethod)#4 (2) {
  ["name"]=>
  string(4) "area"
  ["class"]=>
  string(6) "circle"
 }
}

我们还可以通过getconstructor()来单独获取类的构造方法,其返回值为一个reflectionmethod对象。

$constructor = $reflectionclass->getconstructor();

反射出方法的参数

$parameters = $constructor->getparameters();

其返回值为reflectionparameter对象构成的数组。

array(2) {
 [0]=>
 object(reflectionparameter)#3 (1) {
  ["name"]=>
  string(5) "point"
 }
 [1]=>
 object(reflectionparameter)#4 (1) {
  ["name"]=>
  string(6) "radius"
 }
}

依赖注入

好了接下来我们编写一个名为make的函数,传递类名称给make函数返回类的对象,在make里它会帮我们注入类的依赖,即在本例中帮我们注入point对象给circle类的构造方法。

//构建类的对象
function make($classname)
{
  $reflectionclass = new reflectionclass($classname);
  $constructor = $reflectionclass->getconstructor();
  $parameters = $constructor->getparameters();
  $dependencies = getdependencies($parameters);
  
  return $reflectionclass->newinstanceargs($dependencies);
}

//依赖解析
function getdependencies($parameters)
{
  $dependencies = [];
  foreach($parameters as $parameter) {
    $dependency = $parameter->getclass();
    if (is_null($dependency)) {
      if($parameter->isdefaultvalueavailable()) {
        $dependencies[] = $parameter->getdefaultvalue();
      } else {
        //不是可选参数的为了简单直接赋值为字符串0
        //针对构造方法的必须参数这个情况
        //laravel是通过service provider注册closure到ioccontainer,
        //在closure里可以通过return new class($param1, $param2)来返回类的实例
        //然后在make时回调这个closure即可解析出对象
        //具体细节我会在另一篇文章里面描述
        $dependencies[] = '0';
      }
    } else {
      //递归解析出依赖类的对象
      $dependencies[] = make($parameter->getclass()->name);
    }
  }

  return $dependencies;
}

定义好make方法后我们通过它来帮我们实例化circle类的对象:

$circle = make('circle');
$area = $circle->area();
/*var_dump($circle, $area);
object(circle)#6 (2) {
 ["radius"]=>
 int(1)
 ["center"]=>
 object(point)#11 (2) {
  ["x"]=>
  int(0)
  ["y"]=>
  int(0)
 }
}
float(3.14)*/

通过上面这个实例我简单描述了一下如何利用php类的反射来实现依赖注入,laravel的依赖注入也是通过这个思路来实现的,只不过设计的更精密大量地利用了闭包回调来应对各种复杂的依赖注入。

源码分享:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网