What is DI dependency injection? The following article will give you an in-depth understanding of DI dependency injection in php. I hope it will be helpful to you!
Dependency Injection DI
In fact, it essentially means Dependence on the class is completed through the constructorAutomatic injection
. There is an interdependence relationship between the two classes. The method of passing parameters is called
injection
When you need to use another class in one class , often the following operations are performed
class in the
container class, I need to instantiate it before use
, which can easily lead to later
maintenance difficulties
cannot work without external classes. This is called
too high coupling
<?php class container { private $adapter; public function __construct() { $this->adapter = new adapter(); } }
, mainly for
decoupling
The parameters of the operation are
objects, not ordinary parameters. Do you have a better understanding?
<?php class container { private $adapter; public function __construct(adapter $adapter) { $this->adapter = $adapter; } }
, at this time, dependency injection has been optimized
Through the magic method, Set the object
<?php class container { public $instance = []; public function __set($name, $value) { $this->instance[$name] = $value; } } $container = new container(); $container->adapter = new adapter(); $container->autofelix = new autofelix();
, which is mainly used to
inject the class you want to operate
of the container
<?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); //我是调度器
inject the instantiated objects into the container
, so that the object will not be instantiated and injected. When you need to use it yourself, instantiate it again, which can reduce
Loss of server resources
<?php $container = new container(); $container->adapter = new adapter(); //高阶优化 $container = new container(); $container->adapter = function () { return new adapter(); };
PHP Video Tutorial"
The above is the detailed content of An article to talk about DI dependency injection in php. For more information, please follow other related articles on the PHP Chinese website!