您可能想要查看Ralph Schindler's Zend\Di examples,其中涵盖了所有各种Zend\Di
用例。
我也started working on the Zend\Di documentation,但从来没有完成它,因为我太忙了其他的东西(最终会再次捡起来)。
setter注入(执行):
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注入(从给定的参数):
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'
接口注射。从*Aware*
接口as defined in the introspection strategyZend\Di
发现的注射方法:
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
注释注射。 Zend\Di
通过注释发现注射方法:
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
谢谢您的详细解答!我想得到的是ZF2教程的“完成” - 这就是为什么我用“教程**”中的类编写“示例**”的原因。所以我已经准备编辑你的例子,以便使它们适应教程。但教程似乎不是最新的。它使用类/方法('getInstanceManager()','AggregateDefinition'),它不存在于框架中(不再?)。完成包含此类错误的教程是没有意义的。它应该首先被纠正。但是对于这项任务我还没有足够的知识。无论如何+1为你的例子。 – automatix 2013-03-01 03:26:59
@automatix不确定你刚刚要求我做什么......这些例子代表你的问题的3个请求注入方法。如果您有时间撰写文档,请执行操作!正如您所看到的,“Zend \ Di”文档不完整,因为我被卡住了。 – Ocramius 2013-03-01 09:17:34
我无法更正教程(技巧问题,上面的:)),但是我在GitHub上打开了一个[issue](https://github.com/zendframework/zf2-documentation/issues/703)。 – automatix 2013-03-01 13:47:28