Dependency Injection: Only for single-instance objects?
- by HappyDeveloper
What if I want to also decouple my application, from classes like Product or User? (which usually have more than one instance)
Take a look at this example:
class Controller {
public function someAction() {
$product_1 = new Product();
$product_2 = new Product();
// do something with the products
}
}
Is it right to say that Controller now depends on Product?
I was thinking that we could decouple them too (as we would with single-instance objects like Database)
In this example, however ugly, they are decoupled:
class Controller {
public function someAction(ProductInterface $new_product) {
$product_1 = clone $new_product;
$product_2 = clone $new_product;
// do something with the products
}
}
Has anyone done something like this before? Is it excessive?