Home >Backend Development >PHP Tutorial >Detailed introduction to dependency injection in PHP

Detailed introduction to dependency injection in PHP

王林
王林Original
2019-11-08 11:42:002380browse

Detailed introduction to dependency injection in PHP

Dependency injection principle:

Dependency injection is a method that allows us to decouple from hard-coded dependencies so that we can A software design pattern that can be modified at compile time. In short, it allows us to more conveniently call the associated class in the class method.

Example explanation:

Suppose there is a class like this:

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

If we want to use the index method we need to do this:

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

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

$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 "depend on" and then "inject" them into the method as parameter values.

The dependencyInjection class completes 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(&#39;/> ([^ ]*)/&#39;,$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 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();
}

Recommended tutorial: PHP video tutorial

The above is the detailed content of Detailed introduction to dependency injection in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn