2013-02-28 33 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