What is dependency injection? This article will take you to understand dependency injection in PHP, introduce the reasons for dependency injection, and the application of dependency injection. I hope it will be helpful to you!
1. What is Dependency Injection (DI)
II , The reason why dependency injection appears
<?php class container { private $adapter; public function __construct() { $this->adapter = new adapter(); } }
3. Simple dependencies Injection
<?php class container { private $adapter; public function __construct(adapter $adapter) { $this->adapter = $adapter; } }
<?php class container { public $instance = []; public function __set($name, $value) { $this->instance[$name] = $value; } } $container = new container(); $container->adapter = new adapter();
5. Application of Dependency Injection
<?php class container { public $instance = []; public function __set($name, $value) { $this->instance[$name] = $value; } } class adapter { public $name = '我是调度器'; } $container = new container(); $container->adapter = new adapter(); class autofelix { private $container; public function __construct(container $container) { $this->container = $container; } public function who($class) { return $this->container->instance[$class]->name; } } $autofelix = new autofelix($container); $who = $autofelix->who('adapter'); var_dump($who); //我是调度器
6. High-level optimization
In the above application, we directly inject the instantiated objects into the container.<?php $container = new container(); $container->adapter = new adapter(); //高阶优化 $container = new container(); $container->adapter = function () { return new adapter(); };
Recommended learning: "PHP Video Tutorial
The above is the detailed content of Learn more about dependency injection in PHP and see how to apply it. For more information, please follow other related articles on the PHP Chinese website!