所属分类: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中的依赖注入,看看怎么应用的详细内容,更多请关注zzsucai.com其它相关文章!