m4k31t
m4k31t

Reputation: 33

Dependency injection - is there an alternative to this very large constructor?

Shortly i decided to go for the Dependency Injection technique for a new PHP application i am about to write.

However, I am not entirely sure i understand it enough. My problem is, the baseClass has a dependency on various items, while a lot of different classes will need to extend it. For example:


namespace system;

class baseClass
{
 protected $logger;
 protected $filter;
 protected $database;
 protected $session;


 public function __construct(LoggerInterface $logger, filterInterface $filter, databaseInterface $database, sessionInterface $session)
 {
  $this->logger = $logger;
  $this->filter = $filter;
  $this->database = $database;
  $this->session = $session;
 }
}

Most classes will need the logger, filter etc for doing their jobs: the filter class for example handles escaping / validating, which is something I will need through the whole project.

The problem i predict is, when (nearly) all objects extend this baseClass, everytime i need to instantiate even a pretty simple class (but not as simple as to not need the items described above of course) i get to deal with a constructor that may take a lot of parameters.

When, for example, creating an object of class 'car', this would be OK to me:


$car = new Car($color,$amountOfWheels);

but this seems rather messy to me:


$car = new Car($logger, $filter, $database, $session, $color, $amountOfWheels);

I am looking for a solution to this problem, while not violating the DI paradigm of course. Maybe some sort of factory pattern would help, but creating a factory class for every little object seems a bit overkill to me..?

Upvotes: 3

Views: 533

Answers (1)

Todd R
Todd R

Reputation: 18516

How about using a DbContext object:

$dbContext = new DbContext($logger, $filter, $database, $session);

Then your "Car" is:

$car = new Car($dbContext, $color, $amountOfWheels);

Upvotes: 4

Related Questions