基于PHP构造函数的依赖注入vs new。哪一个更有效率?

时间:2016-04-11 11:32:02

标签: php dependency-injection php-di

有两种类型的依赖注入http://www.javatpoint.com/dependency-injection-in-spring

  1. 基于构造函数的依赖注入
  2. 基于Setter的依赖注入
  3. 然而,以下哪项更有效?为什么?或者它们是否相同?换句话说,依赖注入vs new对象?

    class User
    {
       private $departmentRepo;
    
       public function __construct()
       {
           $this->departmentRepo = new DepartmentRepository();
       }
    }
    
    // OR
    
    class User
    {
       private $departmentRepo;
    
       public function __construct(DepartmentRepository $departmentRepo)
       {
         $this->departmentRepo = $departmentRepo;
       }
    }
    

    修改

    @Chetan Ameta,Federico,Sougata Dependency injection through constructors or property setters?更多地是关于使用哪种依赖方法。后面的问题是关于证明使用哪种DI方法(Constructor或Setter / Getter)。

    然而,我的问题是关于DI与新对象的关系。我们为什么要使用DI?为什么不只是new类并使用该对象? 注意:在我的问题中,示例代码是在PHP中。有了PHP和JavaSpring的经验,我在两种语言中使用DI或OOP都没有太大区别。

0 个答案:

没有答案
相关问题