Analysis of PHP class reflection to implement the dependency injection process, analysis of php class reflection

Source: Internet
Author: User

Analysis of PHP class reflection to implement the dependency injection process, analysis of php class reflection

PHP has a complete reflection API that provides the ability to reverse engineer classes, interfaces, functions, methods, and extensions. Through reflection of classes, we can know how a class is defined, what attributes it has, and what parameters it has for methods and methods, the path of a class file and other important information. Because many PHP frameworks reflect classes, dependency injection can automatically resolve the dependency between classes. This makes development easier. This article mainly explains how to use class Reflection to implement Dependency Injection, and does not describe every API in PHP Reflection one by one. For details about API reference, refer to the official documentation.

For better understanding, we can use an example to look at reflection of classes and how to implement dependency injection.

The following class represents a point in the coordinate system, which has two attributes: x and 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;  }}

Next, this class represents the Circle. We can see that there is a parameter in its constructor that is of the Point class, that is, the Circle class is dependent on the Point class.

Class Circle {/*** @ var int */public $ radius; // radius/*** @ var Point */public $ center; // const PI = 3.14; public function _ construct (Point $ point, $ radius = 1) {$ this-> center = $ point; $ this-> radius = $ radius;} // print the coordinates of the dot. public function printCenter () {printf ('center coordinate is (% d, % d )', $ this-> center-> x, $ this-> center-> y);} // calculate the circular area public function area () {return 3.14 * pow ($ this-> radius, 2 );}}
ReflectionClass

Next we use reflection to reverse engineer the Circle class.

Pass the name of the Circle class to reflectionClass to instantiate an object of the ReflectionClass.

$ ReflectionClass = new reflectionClass (Circle: class); // return the following object (ReflectionClass) #1 (1) {["name"] => string (6) "Circle "}

Returns a constant of the class.

$reflectionClass->getConstants();

Returns an associated array consisting of constant names and values.

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

Get attributes through reflection

$reflectionClass->getProperties();

Returns an array composed of ReflectionProperty objects.

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" }}

Reflects the methods defined in the class.

$reflectionClass->getMethods();

Returns an array composed of reflemethod method objects.

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" }}

You can also use getConstructor () to obtain the class constructor. The returned value is a ReflectionMethod object.

$constructor = $reflectionClass->getConstructor();

Parameters of the Reflection Method

$parameters = $constructor->getParameters();

The returned value is an array composed of ReflectionParameter objects.

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

Dependency Injection

Now, we will compile a function named make and pass the class name to the object of the class returned by the make function. In make, it will help us inject class dependencies, in this example, the Point object is injected to the constructor of the Circle class.

// Construct the Class Object function make ($ className) {$ reflectionClass = new ReflectionClass ($ className); $ constructor = $ reflectionClass-> getConstructor (); $ parameters = $ constructor-> getParameters (); $ dependencies = getDependencies ($ parameters); return $ reflectionClass-> newInstanceArgs ($ dependencies );} // dependency parsing function getDependencies ($ parameters) {$ dependencies = []; foreach ($ parameters as $ parameter) {$ dependency = $ parameter-> getClass (); if (is_null ($ dependency) {if ($ parameter-> isdefavalueavailable () {$ dependencies [] = $ parameter-> getDefaultValue ();} else {// is not an optional parameter. In order to simply assign a value to the string 0 // required parameter for the constructor, laravel registers closure to IocContainer through the service provider, // In closure, return new Class ($ param1, $ param2) to return the instance of the class // then call back the closure during make to parse the object // The specific details will be described in another article $ dependencies [] = '0 ';}} else {// recursively parses the dependent Class Object $ dependencies [] = make ($ parameter-> getClass ()-> name) ;}} return $ dependencies ;}

After the make method is defined, we can use it to instantiate the objects of the Circle class:

$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)*/

Through the above example, I briefly described how to use PHP class reflection to implement dependency injection. Laravel's dependency injection is also implemented through this idea, but the design is more precise and uses the closure callback to deal with a variety of complex dependency injection.

Source code sharing: https://github.com/kevinyan815/php_reflection_dependency_injection_demo/blob/master/reflection.php

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.