2

There are two types of Dependency injection http://www.javatpoint.com/dependency-injection-in-spring

  1. Constructor-based dependency injection
  2. Setter-based dependency injection

However Which one of the following is more efficient and why? or are they Same?, in other words Dependency Injection vs newing the object?

class User
{
   private $departmentRepo;

   public function __construct()
   {
       $this->departmentRepo = new DepartmentRepository();
   }
}

// OR

class User
{
   private $departmentRepo;

   public function __construct(DepartmentRepository $departmentRepo)
   {
     $this->departmentRepo = $departmentRepo;
   }
}

EDIT

@Chetan Ameta, Federico, Sougata Dependency injection through constructors or property setters? is more about which of the Dependency method to use. The later question is about justifying which of the DI method to use (Constructor or Setter/Getter).

However my question is about DI vs new ing the object. Why do we use DI? why not Just new the class and use the object? Note: In my question, example code is in PHP. Having experience PHP and JavaSpring, I don't see much difference in using DI or OOP in both the languages.

Community
  • 1
  • 1
Manjunath Reddy
  • 1,039
  • 2
  • 13
  • 22

0 Answers0