mardi 28 juillet 2015

Right pattern and dependency injection

I have a problem with deciding the right way or writing a module. I THINK I know the theory behind the dependency injection and what are it's advantages but perhaps I am mixing something or do not have a very clear image.

A rather simplified example would be :

I have a model for my object and here I inject a validator class that handles the various validations :

// index.php
// ......
$model = new Model();
$model->setValidator(new Validator());
$model->getValidator()->exampleValidateCall();
// ......

// validator.php
class Validator implements ValidatorInterface {

   //.....

   public function exampleValidateCall() {
      // code goes here
   }
}

My problem here is that I need for instance access to the settings entity witch defines the behaviour of the model. Because the settings define the model, I do not think that I should pass theese settings inside the validator.

One option would be that the validator will extend the model, but I think that would be bad practice ( because the whole dependency injection concept goes kaboom... or not ? ). I could do something like :

$model->setValidator(new Validator($model->getSettings()));

but this looks even more idiotic from my point of view.

One better solution, again from my point of view, would be to pass a new object to the validator constructor

$model->setValidator(new Validator(new Settings()));

because in reality settings do not have dependency with the model, but that seems to complicate a little too much. And also the settings entity is constructed inside the model because it defies some of the behaviours.

What would be the best practice in writing these objects / dependencies ?

Aucun commentaire:

Enregistrer un commentaire