Detailed Explanation of Dependency Injection Instance in php

  • 2021-12-13 16:35:42
  • OfStack

This article illustrates dependency injection in php. Share it for your reference, as follows:

Dependency injection is a software design pattern that allows us to decouple from hard-coded dependencies so that we can modify them at run time or compile time.

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

If you are interested, you can refer to the explanation of "dependency injection" in "The Way of PHP".
http://laravel-china.github.io/php-the-right-way/#dependency_injection

In short, it makes it easier for us to call the class associated with it in the method of the class.

Suppose we have one such class


class Test
{
 public function index(Demo $demo,Apple $apple){
  $demo->show();
  $apple->fun();
 }
}

If we want to use the index method, we generally need to do so.


$demo = new Demo();
$apple = new Apple();
$obj = new Test();
$obj->index($demo,$apple);

Is the index method troublesome to call? The above method only has two parameters. If there are more parameters, we will instantiate more objects as parameters. If we introduce "dependency injection", the calling method will look like the following.


$obj = new dependencyInjection();
$obj->fun("Test","index");

In our example above, the index method of the Test class relies on the Demo and Apple classes.

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

The dependencyInjection class does this dependency injection task.


<?php
/**
 * Created by PhpStorm.
 * User: zhezhao
 * Date: 2016/8/10
 * 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 model. If we use dependency injection and automatic loading of classes, we can use it as follows.


public function index(UserModel $userModel,MessageModel $messageModel){
 $userList = $userModel->getAllUser();
 $messageList = $messageModel->getAllMessage();
}

Gray is often convenient ~

More readers interested in PHP can check out 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" and "Summary of php Common Database Operation Skills"

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


Related articles: