Symfony 3不会将EntityManager注入服务

时间:2016-10-01 15:50:39

标签: php doctrine-orm symfony

我使用symfony 3.1。

我试图将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 

为什么它没有在服务类中注入学说?

服务

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"]

服务使用

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

3 个答案:

答案 0 :(得分:2)

您没有使用服务,只有课程。要在命令中使用服务,请将其扩展为ContainerAwareCommand,然后您可以通过它调用您的服务:

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

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

答案 1 :(得分:0)

如@malcolm所述,您还需要将命令注册为服务。

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

答案 2 :(得分:-1)

嗯,您需要在TeamsWriter中使用Doctrine\ORM\EntityManager;