PHP系の反射による依存注入の実現方法を浅く分析した.

5955 ワード

PHPは完全な反射APIを有し、クラス、インタフェース、関数、方法、および拡張を逆方向エンジニアリングする能力を提供する.クラスの反射によって提供される能力は、クラスがどのように定義されているのか、どのような属性があるのか、どのような方法、方法にどのようなパラメータがあるのか、クラスファイルのパスが何なのかなど、重要な情報を知ることができます.クラスの反射が多いPHPフレームワークによって依存注入によるクラスとクラス間の依存関係の自動解決が実現されることもあり,これは我々の普段の開発に大きな便利さをもたらした.本文は主にクラスの反射を利用して依存注入(Dependency Injection)を実現する方法を説明し、PHP Reflectionの各APIについて逐条説明するわけではありません.詳細なAPIの参考情報は公式ドキュメントを参照してください.
ここで実現した依存注入は非常に簡単で、実際の開発に応用できないことを改めて宣言し、laravelフレームワークのサービスコンテナ(IocContainer)を詳しく紹介する予定で、そこでLaravelのサービスコンテナがどのように依存注入を実現しているかを見てみましょう.
よりよく理解するために,クラスの反射と依存注入をどのように実現するかを一例で見た.次のクラスは座標系の1つの点を表し、2つの属性横座標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 = 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"
  }
}

クラスの構造方法は、ReflectionClassオブジェクトを1つのgetConstructor()オブジェクトとして返すこともできます.
$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"
  }
}

依存注入
さて、次に、ReflectionMethodという関数を作成し、クラス名をmake関数に渡してクラスのオブジェクトを返します.makeでは、クラスの依存を注入してくれます.つまり、この例では、makeオブジェクトをPointクラスの構造方法を注入してくれます.
//      
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;
}

定義済みCircleメソッドを使用して、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の依存注入もこの考え方によって実現されたが,閉包コールバックをより精密に利用して様々な複雑な依存注入に対応するように設計されただけで,具体的な詳細を整理する必要があるものがあるので、最近別の文章で詳しく説明します.
本明細書のサンプルコードのダウンロードリンク
原文:https://segmentfault.com/a/1190000012696784