首页 > 代码库 > 依赖注入学习-01
依赖注入学习-01
<?php/* 无Di容器的写法 class example { private $_db; function getList(){ $this->_db->query("......");//这里具体sql语句就省略不写了 } //从外部注入db连接 function setDb($connection){ $this->_db = $connection; } } //调用 $example = new example(); $example->setDb(Factory::getDb());//注入db连接 $example->getList(); class Factory { public static function getExample(){ $example = new example(); $example->setDb(Factory::getDb());//注入db连接 $example->setFile(Factory::getFile());//注入文件处理类 $example->setImage(Factory::getImage());//注入Image处理类 return $expample; } } 实例化example时变为 $example=Factory::getExample(); $example->getList();*/header("Content-Type:text/html;charset=utf-8");class Di{ private $_factory; public function set($id,$value){ $this->_factory[$id] = $value; } public function get($id){ $value = $this->_factory[$id]; return $value(); }}class User{ private $_username; function __construct($username="") { $this->_username = $username; } function getUserName(){ return $this->_username;//$this->_username = $username; }}$di = new Di();$di->set("zhangsan",function(){ return new User(‘张三‘);}); //$this->_factory[‘zhangsan‘] = new User(‘张三‘);$di->set("lisi",function(){ return new User("李四"); }); //$this->_factory[‘lisi‘] = new User(‘李四‘);echo $di->get("zhangsan")->getUserName();// $value = http://www.mamicode.com/$this->_factory[‘zhangsan‘] = new User(‘张三‘)->getUserName();echo $di->get("lisi")->getUserName();// $value = http://www.mamicode.com/$this->_factory[‘lisi‘] = new User(‘李四‘)->getUserName();/* $data = http://www.mamicode.com/new User(‘张三‘);>*/
依赖注入学习-01
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。