PHP class Reflection Implementation Dependency Injection process detailed

Source: Internet
Author: User
Tags php framework
PHP has a complete reflection API that provides the ability to reverse engineer classes, interfaces, functions, methods, and extensions. The ability to provide through the reflection of a class enables us to know how a class is defined, what properties it has, what methods it has, what parameters it has, and what the path to the class file is, such as important information. Also formally because of the reflection of a lot of PHP framework to implement dependency injection automatically solve the dependency between classes and classes, which has brought great convenience to our development.

This article is mainly about how to use the reflection of the class to implement dependency injection (Dependency injection), and will not go through each PHP reflection each API, Detailed API reference information please refer to the official documentation this article mainly and everyone introduces the PHP class reflection to realize the dependency injection process and related knowledge points to share, interested in this friend followed the small series of learning, hope to help everyone.

To get a better understanding, we look at the reflection of the class through an example, and how to implement dependency injection.

The following class represents a point in the coordinate system, with two attribute axes x and ordinate 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 the point ' s coordinate   */
  
   public function __construct ($x = 0, $y = 0)  {    $this->x = $x;    $this->y = $y;  }}
  

Next the class represents a circle, and you can see that in its constructor there is a parameter in 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;//Center point  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);  }  Calculates the area of the circle public  function areas ()  {    return 3.14 * POW ($this->radius, 2);}  }

Reflectionclass

Below we reverse engineer the Circle class by reflection.

Pass the name of the Circle class to Reflectionclass to instantiate an object of the Reflectionclass class.


$reflectionClass = new Reflectionclass (circle::class);//The return value is as follows object (Reflectionclass) #1 (1) {["Name"]=> string (6) " Circle "}

Constants that reflect a class


$reflectionClass->getconstants ();

Returns an associative array consisting of a constant name and value


Array (1) {["PI"]=> Float (3.14)}

Get Properties by Reflection


$reflectionClass->getproperties ();

Returns an array 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"}

Reflect a method defined in a class


$reflectionClass->getmethods ();

Returns an array of Reflectionmethod objects


Array (3) {[0]=> object (Reflectionmethod) #2 (2) {  ["name"]=>  string (one) "__construct"  ["Class"]= >  string (6) "Circle"} [1]=> object (Reflectionmethod) #3 (2) {  ["name"]=>  string (one) "Printcenter "  [" Class "]=>  string (6)" Circle "} [2]=> object (Reflectionmethod) #4 (2) {  [" name "]=>  string (4) "Area"  ["Class"]=>  string (6) "Circle"}}

We can also get the constructor of the class separately by GetConstructor (), whose return value is a Reflectionmethod object.


$constructor = $reflectionClass->getconstructor ();

Parameters of the reflected method


$parameters = $constructor->getparameters ();

The return value is an array 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

All right, then we'll write a function called make, passing the class name to the object that makes the function return class, and in make it will inject the dependency of the class, that is, in this case, inject the point object into the method of constructing the Circle class.


Construct the object function make ($className) {$reflectionClass = new Reflectionclass ($className) of the class;  $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->isdefaultvalueavailable ()) {$dependencies [] = $parameter->ge      Tdefaultvalue ();         } else {//is not an optional parameter for simple direct assignment to string 0//Required parameter for construction method This condition//laravel is registered closure to Ioccontainer through service provider, In closure, you can return an instance of the class by returning the new class ($param 1, $param 2)//And then callback the closure at make to resolve the object//specific details I'll be in another article      Inside description $dependencies [] = ' 0 ';    }} else {//recursively resolves the object of the dependent class $dependencies [] = Make ($parameter->getclass ()->name); }} return $depeNdencies;} 

After defining the Make method, we use it to instantiate the object 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) */
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.