views:

43

answers:

1

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..?

+2  A: 

How about using a DbContext object: $dbContext = new DbContext($logger, $filter, $database, $session);

Then your "Car" is $car = new Car($dbContext, $color, $amountOfWheels);

Todd R
I agree with what Todd proposes essentially. The things youre injecting here have no place directly injected into a model IMO. The realate to the DB connection, or context as Todd termed it. But even then i personally thing this injection should be optional, and that even if it means fetching the default connection/context from an outside registry or connection manager class. I mean its good to minimize dependencies as much as possible, but sometimes i think one can go too far, just creating complexity/bloat than there needs to be.
prodigitalson
Seems indeed a good option to me. Although i fear a bit that the DbContect object might become a sort of 'global' registry. @prodigitalson: that is also a good option, but violates the DI paradigm a bit. But maybe its not that bad, if it occurs only on one baseClass.
m4k31t