¿Mezclar servicios y objetos hoja en el constructor para la inyección de dependencia?

I am attempting to make my code as testable as possible, which means using dependency injection correctly.

I have read that it's okay to use new() to instantiate an object, if that object meets certain criteria. Notably - it should not accept a "non newable" in its constructor.

For example, I should be able to go

new Form('signup');

because there is no way that my DI container would know how to create the "signup" form ahead of time.

I can make this work most of the time, but now I'd like the Form to be able to validate itself, using a third party validator, like:

$form->validate()->isValid();

...which means that I would have to pass in a validator service.

I'd really prefer to have the validator included already because most of the time the form will need to be validated, and I'd have to go through the extra work to set the validator on my own otherwise.

Is it okay, in this instance to do:

new Form(Validator $validator,$name); 

preguntado el 09 de marzo de 12 a las 15:03

1 Respuestas

I'd say that any value or object which an object requires in order to be in a valid state is one of that object's dependencies; in your example that would entirely validly include the form's name. I don't think the type of a dependency can be used to say whether it should be injected or not - Martin Fowler en este articulo for instance shows objects having strings injected into them, and DI containers can usually be configured to supply string values.

With this in mind, injecting the validator and the string is fine and entirely correct in my opinion.

respondido 10 mar '12, 18:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.