Dependency injection is one that allows us to decouple from hard-coded dependencies,Software design patterns that can be modified at run time or compile time.

I still don't quite understand what the definition of "dependency injection" above is ...

If you are interested, you can refer to the explanation of "Dependency Injection" in "The Way of PHP".


In short, it is more convenient for us to call the associated class in the method of the class.

Suppose we have a class like this

class test
 public function index (demo $demo, apple $apple) {
  $demo->show ();
  $apple->fun ();

We generally need to do this if we want to use the index method.

$demo=new demo ();
$apple=new apple ();
$obj=new test ();
$obj->index ($demo, $apple);

Is the index method inconvenient to call?The above method just has two parameters,If there are more parameters,We are going to instantiate more objects as parameters.If we introduced "dependency injection", the calling method would look like the following.

$obj=new dependencyinjection ();
$obj->fun ("test", "index");

In our example above,The index method of the test class depends on the demo and apple classes.

"Dependency injection" is to identify the classes that all methods "depends on" and then "inject" them into the method as parameter values.

The dependencyinjection class accomplishes this dependency injection task.

 * created by phpstorm.
 * user:zhezhao
 * date:8/8/2016
 * time:19:18
 * /
class dependencyinjection
 function fun ($classname, $action) {
  $reflectionmethod=new reflectionmethod ($classname, $action);
  $parammeters=$reflectionmethod->getparameters ();
  $params=array ();
  foreach ($parammeters as $item) {
   preg_match ("/>([^] *) /", $item, $arr);
   $class=trim ($arr [1]);
   $params []=new $class ();
  $instance=new $classname ();
  $res=call_user_func_array ([$instance, $action], $params);
  return $res;

In the MVC framework, control sometimes uses multiple models. If we useDependency injectionandClass autoloadingAfter that, we can use it like this.

public function index (usermodel $usermodel, messagemodel $messagemodel) {
 $userlist=$usermodel->getalluser ();
 $messagelist=$messagemodel->getallmessage ();

Gray often convenient ~

  • Previous Detailed installation and use of Spring Boot plugin spring tool suite
  • Next Implementation of MyBatisPlus custom SQL statement