zoukankan      html  css  js  c++  java
  • 依赖注入学习-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 = $this->_factory['zhangsan'] = new User('张三')->getUserName();
    echo $di->get("lisi")->getUserName();// $value = $this->_factory['lisi'] = new User('李四')->getUserName();
    
    
    /* $data = new User('张三');
    echo $data->getUserName(); */

     

  • 相关阅读:
    zz[读书笔记]《Interpretable Machine Learning》
    Xgboost,LightGBM 和 CatBoost
    zz:Xgboost 导读和实战
    bzoj3252: 攻略 优先队列 并查集 贪心
    [BeiJing2009 WinterCamp]取石子游戏 Nim SG 函数
    Playing With Stones UVALive
    Division Game UVA
    [BJWC2011]禁忌 AC 自动机 概率与期望
    [Jsoi2010]连通数 bitset + Floyd
    洛谷P2197 nim游戏模板
  • 原文地址:https://www.cnblogs.com/hellowzd/p/5889849.html
Copyright © 2011-2022 走看看