Home > Article > Backend Development > 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('/> ([^ ]*)/',$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!