什么是依赖注入?本篇文章带大家了解一下PHP中的依赖注入,介绍一下依赖注入出现的原因、依赖注入的应用,希望对大家有所帮助!
一、什么是依赖注入 (DI)
二、依赖注入出现的原因
<?php class container { private $adapter; public function __construct() { $this->adapter = new adapter(); } }
三、简单的依赖注入
<?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();
五、依赖注入的应用
<?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); //我是调度器
六、高阶优化
<?php $container = new container(); $container->adapter = new adapter(); //高阶优化 $container = new container(); $container->adapter = function () { return new adapter(); };
原文地址:https://juejin.cn/post/7004616671864291359
推荐学习:《PHP视频教程》
以上是深入了解PHP中的依赖注入,看看怎么应用的详细内容。更多信息请关注PHP中文网其他相关文章!