2016-08-04 69 views
0

依賴我這種情況如何使用工廠模式注入在Symfony2的

abstract class Importer { 

    const NW = 1; 

    public static function getInstance($type) 
    { 
     switch($type) 
     { 
      case(self::NW): 
      return new NWImporter(); 
      break; 
     } 
    } 

    protected function saveObject(myObject $myObject) 
    { 
     //here I need to use doctrine to save on mongodb 
    } 

    abstract function import($nid); 
} 

class NWImporter extends Importer 
{ 
    public function import($nid) 
    { 
     //do some staff, create myObject and call the parent method to save it 
     parent::saveObject($myObject); 
    } 
} 

,我想使用它們像這樣

$importer = Importer::getInstance(Importer::NW); 
$importer->import($nid); 

我的問題是:如何注入saveObject方法中使用的原則?

感謝

+0

聲明你的類作爲服務傳遞參數'@doctrine.orm.entity_manager你可以在工廠方法注入學說爭論' – DOZ

+0

你能提供一個例子嗎?我已經試過服務 – user3174311

+1

見下面@elkorchianas anwser :) – DOZ

回答

1

您需要將進口配置爲symfony的服務:

services: 
    test.common.exporter: 
     # put the name space of your class 
     class: Test\CommonBundle\NWImporter 
     arguments: [ "@doctrine" ] 

然後NWImporter定義帶有參數的構造函數,將有學說實例

public function __construct($doctrine) 
    { 
    $this->doctrine= $doctrine; 
    } 

與這個解決方案可以避免使用工廠方法,因爲symfony可以爲你做,但如果你想保留它,當你從你的控制器調用$importer = Importer::getInstance(Importer::NW);

abstract class Importer { 

    const NW = 1; 

    public static function getInstance($type, $doctrine) 
    { 
     switch($type) 
     { 
      case(self::NW): 
      return new NWImporter($doctrine); 
      break; 
     } 
    } 

    protected function saveObject(myObject $myObject) 
    { 
     //here I need to use doctrine to save on mongodb 
    } 

    abstract function import($nid); 
} 

然後在你的控制器,你應該做這樣的事情:

$doctrine = $this->container->get('doctrine'); 
$importer = Importer::getInstance(Importer::NW, $doctrine); 
$importer->import($nid); 
+0

我已經嘗試過,但我得到一個錯誤,因爲進口商有「返回新的NWImporter();」期待我傳遞一個參數... – user3174311

+0

您從您的控制器中調用NWImporter :: getInstance()函數嗎? –

+0

是的,我想從控制器調用它,而且,我無法注入到導入程序,因爲NWImporter擴展導入程序,並且構造期望再次參數... – user3174311