(After some very (!) useful links to articles about DI and a basic example) In the chapter "Simplest usage case (2 classes, one consumes the other)" the Zend Framework 2 tutorial "Learning Dependency Injection" provides an example for constructor injection. This one is OK. Then it shows an example of setter injection. But it's not complete (the call / usage part of the example is missing). Examples for interface injection and annotation based injection are missing.
(1) How would look the missing part of the setter injection example? Can someone please moreover write a an (2) interface injection and (3) annotation based injection example with the classes from the tutorial?
Thank you in advance!
You probably want to look into Ralph Schindler's Zend\Di examples, which cover all the various Zend\Di
use cases.
I also started working on the Zend\Di documentation, but never got to finish it because I was too busy with other stuff (will eventually pick it up again).
Setter injection (enforced):
class Foo
{
public $bar;
public function setBar(Bar $bar)
{
$this->bar = $bar;
}
}
class Bar
{
}
$di = new Zend\Di\Di;
$cfg = new Zend\Di\Configuration(array(
'definition' => array(
'class' => array(
'Foo' => array(
// forcing setBar to be called
'setBar' => array('required' => true)
)
)
)
)));
$foo = $di->get('Foo');
var_dump($foo->bar); // contains an instance of Bar
Setter injection (from given parameters):
class Foo
{
public $bar;
public function setBar($bar)
{
$this->bar = $bar;
}
}
$di = new Zend\Di\Di;
$config = new Zend\Di\Configuration(array(
'instance' => array(
'Foo' => array(
// letting Zend\Di find out there's a $bar to inject where possible
'parameters' => array('bar' => 'baz'),
)
)
)));
$config->configure($di);
$foo = $di->get('Foo');
var_dump($foo->bar); // 'baz'
Interface injection. Zend\Di
discovers injection methods from an *Aware*
interface as defined in the introspection strategy:
interface BarAwareInterface
{
public function setBar(Bar $bar);
}
class Foo implements BarAwareInterface
{
public $bar;
public function setBar(Bar $bar)
{
$this->bar = $bar;
}
}
class Bar
{
}
$di = new Zend\Di\Di;
$foo = $di->get('Foo');
var_dump($foo->bar); // contains an instance of Bar
Annotation injection. Zend\Di
discovers injection methods via annotations:
class Foo
{
public $bar;
/**
* @Di\Inject()
*/
public function setBar(Bar $bar)
{
$this->bar = $bar;
}
}
class Bar
{
}
$di = new Zend\Di\Di;
$di
->definitions()
->getIntrospectionStrategy()
->setUseAnnotations(true);
$foo = $di->get('Foo');
var_dump($foo->bar); // contains an instance of Bar