如何在Symfony2中使用Factory Pattern注入依赖项

时间:2016-08-04 14:55:11

标签: symfony doctrine-orm

我有这种情况

// TODO: Create the TextRecognizer
TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();

// TODO: Set the TextRecognizer's Processor.
textRecognizer.setProcessor(new OcrDetectorProcessor(mGraphicOverlay));

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);
    }
}

我的问题是:如何注入要在saveObject方法中使用的doctrine?

感谢

1 个答案:

答案 0 :(得分:1)

您需要将导入程序配置为symfony服务:

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

然后在NWImporter中定义一个带有参数的构造函数,该参数将具有doctrine实例

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

使用此解决方案,您可以避免使用工厂方法,因为symfony会为您执行此操作,但如果您想保留它,当您从控制器调用$importer = Importer::getInstance(Importer::NW);时,可以在工厂方法中注入doctrine参数:< / p>

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);