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(); */

     

  • 相关阅读:
    flask项目--认证方案Json Web Token(JWT)
    分布式设计-集群
    分布式设计-哨兵
    分布式设计--数据库主从
    leetcode 221 Maximal Square
    LeetCode222 Count Complete Tree Nodes
    在windows 、linux下读取目录下所有文件名
    leetcode 229 Majority Element II
    leetcode 233 Number of Digit One
    leetcode 238 Product of Array Except Self
  • 原文地址:https://www.cnblogs.com/hellowzd/p/5889849.html
Copyright © 2011-2022 走看看