(在一些非常(!)有用的关于 DI 的文章和一个基本示例的链接之后)在“最简单的用例(2 个类,一个消耗另一个) ”一章中,Zend Framework 2 教程“学习依赖注入”提供了构造函数的示例注射。这个还行。然后它显示了一个setter 注入的例子。但它并不完整(缺少示例的调用/使用部分)。缺少接口注入和基于注释的注入的示例。
(1) setter 注入示例的缺失部分如何?有人可以用教程中的类写一个(2)接口注入和(3)基于注释的注入示例吗?
先感谢您!
(在一些非常(!)有用的关于 DI 的文章和一个基本示例的链接之后)在“最简单的用例(2 个类,一个消耗另一个) ”一章中,Zend Framework 2 教程“学习依赖注入”提供了构造函数的示例注射。这个还行。然后它显示了一个setter 注入的例子。但它并不完整(缺少示例的调用/使用部分)。缺少接口注入和基于注释的注入的示例。
(1) setter 注入示例的缺失部分如何?有人可以用教程中的类写一个(2)接口注入和(3)基于注释的注入示例吗?
先感谢您!
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