Home>Article>Backend Development> An article to talk about DI dependency injection in php
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 DIIn 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 calledinjectionWhen you need to use another class in one class , often the following operations are performedclass in thecontainerclass, I need to instantiate it before use, which can easily lead to latermaintenance difficultiescannot work without external classes. This is calledtoo high couplingadapter = new adapter(); } }
, mainly fordecouplingThe parameters of the operation areobjects, not ordinary parameters. Do you have a better understanding?adapter = $adapter; } }
, at this time, dependency injection has been optimizedThrough the magic method,Set the objectinstance[$name] = $value; } } $container = new container(); $container->adapter = new adapter(); $container->autofelix = new autofelix();
, which is mainly used toinjectthe class you want to operateof the containerinstance[$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 reduceLoss of server resourcesadapter = new adapter(); //高阶优化 $container = new container(); $container->adapter = function () { return new adapter(); };Recommended study: "
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!