1,843   DesignPatterns

1,依赖,直接在构造方法里实例化依赖

 

    class User{
        public function __construct(){
            // 依赖 database, 由内部构造方法实例化
            $this->database = new database();
        }
    }
    $user = new User();

 

 

2,依赖注入,在外部实例依赖之后,再注入

 

    class User{
        public function __construct(database $database){
            // 依赖注入 database, 由外部实例化后注入
            $this->database = $database;
        }
    }
    $database = new database(); // 依赖注入 database
    $user = new User($database);

 

 

3,依赖注入的好处,修改依赖时不需要修改应用类的代码

    class User{
        public function __construct(){
            // 依赖 database, 由内部构造方法实例化
            $type = 'mysql'; // 修改依赖database,添加参数$type
            $this->database = new database($type);
        }
    }
    $user = new User();

    class User{
        public function __construct(database $database){
            // 依赖注入 database, 由外部实例化后注入
            $this->database = $database;
        }
    }
    $type = 'mysql'; // 修改依赖database,添加参数$type
    $database = new database($type); // 依赖注入 database
    $user = new User($database);

想像一下,如果很多应用类都依赖了database,当需要修改database时,是不是需要到每个应用类里修改这个database;
但是依赖注入只需要在应用类的外部修改database,而且修改一次就行了,不需要改动应用类的代码




Leave a Reply

Your email address will not be published. Required fields are marked *