2013-02-28 32 views
1

(关于DI文章的一些非常有用的链接和一个基本示例)在“Simplest usage case (2 classes, one consumes the other)”一章中,Zend Framework 2教程“Learning Dependency Injection”提供了一个示例为构造注入。这个是好的。然后它显示了一个setter注入的例子。但它不完整(示例的调用/使用部分缺失)。 接口注入示例注释基于注入缺失。Zend Framework 2教程“学习依赖注入”的缺失示例

(1)如何查看setter注入示例的缺失部分?是否有人可以另外写一个(2)接口注入和(3)基于注解的注入示例与教程中的类?

预先感谢您!

回答

4

您可能想要查看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 
+0

谢谢您的详细解答!我想得到的是ZF2教程的“完成” - 这就是为什么我用“教程**”中的类编写“示例**”的原因。所以我已经准备编辑你的例子,以便使它们适应教程。但教程似乎不是最新的。它使用类/方法('getInstanceManager()','AggregateDefinition'),它不存在于框架中(不再?)。完成包含此类错误的教程是没有意义的。它应该首先被纠正。但是对于这项任务我还没有足够的知识。无论如何+1为你的例子。 – automatix 2013-03-01 03:26:59

+0

@automatix不确定你刚刚要求我做什么......这些例子代表你的问题的3个请求注入方法。如果您有时间撰写文档,请执行操作!正如您所看到的,“Zend \ Di”文档不完整,因为我被卡住了。 – Ocramius 2013-03-01 09:17:34

+0

我无法更正教程(技巧问题,上面的:)),但是我在GitHub上打开了一个[issue](https://github.com/zendframework/zf2-documentation/issues/703)。 – automatix 2013-03-01 13:47:28