Dependency Injection: Only for single-instance objects?

Posted by HappyDeveloper on Programmers See other posts from Programmers or by HappyDeveloper
Published on 2011-11-13T20:03:15Z Indexed on 2011/11/14 2:04 UTC
Read the original article Hit count: 284

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?

© Programmers or respective owner

Related posts about php

Related posts about dependency-injection