2016-10-01 3 views
-1

私はsymfony 3.1を使用しています。symfony 3はサービスにEntityManagerをインジェクトしません

サービスクラスにEntityManagerを挿入しようとしています。私はすべてドキュメントのようにしましたが、引き続き例外を取得し続けます。

[Symfony\Component\Debug\Exception\FatalThrowableError]                          
    Type error: Argument 1 passed to AppBundle\Writers\TeamsWriter::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /ho 
    me/admin_u/Documents/test_project/src/AppBundle/Command/ParseMatchesCommand.php on line 54 

Doctrineをサービスクラスに挿入しないのはなぜですか?

サービス

private $entity_manager; 

    /** 
    * TeamsWriter constructor. 
    * @param EntityManager $entity_manager 
    */ 
    public function __construct(EntityManager $entity_manager) 
    { 
     $this->entity_manager = $entity_manager; 
    } 

Services.yml

services: 
teams_writer: 
    class: AppBundle\Writers\TeamsWriter 
    arguments: ["@doctrine.orm.entity_manager"] 

あなたがサービスBを使用していませんでした

protected function execute(InputInterface $input, OutputInterface $output) 
{ 
    $parser = new TeamsParser(); 
    $data = $parser->execute(); 
    $writer = new TeamsWriter(); 
    $writer->store($data); 
} 

答えて

2

サービスの利用それはクラスだけです。あなたのコマンドでサービスを利用するには、ContainerAwareCommandによってそれを拡張し、あなたはそれからサービスあなたを呼び出すことができます。

@malcolmで述べたように
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; 

class MyCommand extends ContainerAwareCommand 
{ 
    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $writer = $this->getContainer()->get('teams_writer'); 
+0

あるいは、パーサーとライターを直接コマンドに挿入して、 ntainer。 – Cerad

+0

ContainerAwareCommandは良い方法です。 – COil

0

は、あなたにもサービスとしてコマンドを登録する必要があります。

symfony 3.3は、数日後に近づいていますので、its new Dependency Injection featuresを使用します。私はあなたがすでに掲載してコードを書き換えます:

Services.yml

services: 
    _defaults: 
     autowire: true # all services here will be autowired = no need for manual service naming in constructor 
     autoconfigure: true # this will add tags to all common services (commands, event subscribers, form types...) 

    AppBundle\Writers\TeamsWriter: ~ # short notation for a service 
    AppBundle\Parsers\TeamsParser: ~ 

    AppBundle\Command\YourCommand: ~ 

サービスの利用

use AppBundle\Parsers\TeamsParser; 
use AppBundle\Writers\TeamsWriter; 

final class YourCommand extends Command 
{ 

    // ... use constructor injection to get your dependencies 

    public function __construct(TeamsWriter $teamsWriter, TeamsParser $teamsParser) 
    { 
     $this->teamsWriter = $teamsWriter; 
     $this->teamsParser = $teamsParser; 
     parent::__construct(); // this is need if this is console command, to setup name and description 
     // kinda hidden dependency but it is the way it works now 
    } 

    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $data = $this->teamsParser->execute(); 
     $this->teamsWriter->store($data); 
    }  
} 
-1

あなたのTeamsWriterでDoctrine\ORM\EntityManager;を使用する必要がフム、

関連する問題