SuprF1y
SuprF1y

Reputation: 100

Zend Framework 2 dependency injection via interface

How do I specify which implementation of an interface a specific class needs for setter injection? I have a working eg for constructor injection but not for setters.

class Lister1 {
    public $finder;
    public function setFinder(Finder $finder){
        $this->finder = $finder;
    }
}

interface Finder {
    public function findAllByName($name);
}

class FinderImpl1 implements Finder {
    public function findAllByName($name) {}
}

Now for the above the following code works.

$di = new Di();
$di->instanceManager()->addTypePreference(
    'Finder', 
    'FinderImpl1'
);
$lister = $di->get('Lister1');

But what if I have the following as well

class Lister2 extends Lister1{
}
class FinderImpl2 implements Finder {
    public function findAllByName($name) {//assume a different impl}
}

So Lister1 needs FinderImpl1 injected & Lister2 needs FinderImpl2 injected.
Can we add a type preference on a per-class basis?
I had a look at the unit tests that ship with zf2 and nothing leaped out.

Upvotes: 0

Views: 573

Answers (1)

David
David

Reputation: 20115

It looks like you've found Ralph's DI examples. Good. That was going to be my first suggestion. :)

I may be wrong (been a while since I used DI), but it might be simpler than you are thinking.

Using setter injection like so:

$di = new Zend\Di\Di;
$di->configure(new Zend\Di\Config(array(
    'instance' => array(
        'Lister1' => array(
            'parameters' => array(
                'finder' => 'FinderImpl1',
            ),
        ),
        'Lister2' => array(
            'parameters' => array(
                'finder' => 'FinderImpl2',
            ),
        ),
    )
)));

If you were going to define an instance of an interface, then you would need to worry about setting a "preference"; in which case if you had something tricky, you might consider using some aliases along with the preference definition.

Upvotes: 1

Related Questions