Dependency Injection Example for php Reflection Learning

  • 2021-12-11 17:36:43
  • OfStack

This paper illustrates the dependency injection of php reflection learning. Share it for your reference, as follows:

Look at the code first:


<?php
if (PHP_SAPI != 'cli') {
  exit('Please run it in terminal!');
}
if ($argc < 3) {
  exit('At least 2 arguments needed!');
}
$controller = ucfirst($argv[1]) . 'Controller';
$action = 'action' . ucfirst($argv[2]);
//  Check if a class exists 
if (!class_exists($controller)) {
  exit("Class $controller does not existed!");
}
//  Gets the reflection of a class 
$reflector = new ReflectionClass($controller);
//  Check if a method exists 
if (!$reflector->hasMethod($action)) {
  exit("Method $action does not existed!");
}
//  Take the constructor of the class 
$constructor = $reflector->getConstructor();
//  Take the parameters of the constructor 
$parameters = $constructor->getParameters();
//  Traversal parameter 
foreach ($parameters as $key => $parameter) {
  //  Gets the class declared by the parameter 
  $injector = new ReflectionClass($parameter->getClass()->name);
  //  Instantiate the parameter declaration class and fill in the parameter list 
  $parameters[$key] = $injector->newInstance();
}
//  Using parameter list instances  controller  Class 
$instance = $reflector->newInstanceArgs($parameters);
//  Execute 
$instance->$action();
class HelloController
{
  private $model;
  public function __construct(TestModel $model)
  {
    $this->model = $model;
  }
  public function actionWorld()
  {
    echo $this->model->property, PHP_EOL;
  }
}
class TestModel
{
  public $property = 'property';
}

(The above code is not original) Save the above code as run. php

Operation mode, executed under the terminal php run.php Hello World

As you can see, we're going to execute WorldAction under HelloController,
The constructor of HelloController requires an object of type TestModel,

With php reflection, we realize the automatic injection of TestModel objects.

The above example is similar to the process of 1 request distribution, which is part 1 of the distribution of routing requests. If we want to receive 1 request address, for example:/Hello/World

It means to execute the WorldAction method under HelloController.

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: