Symfony 4:命令学说

T. *_*ong 4 php doctrine symfony

我正在使用symfony 4,并且如果我在Command类中,我想访问一个实体的存储库。没有任何功能getDoctrine

我已经通过控制台创建了一个实体,所以我有了一个实体和一个存储库。

有人知道我如何访问存储库吗?

Jam*_*lin 19

Symfony 4 的官方建议是只自动装配你需要的东西。因此,与其注入 ContainerInterface 并从中请求 EntityManager,不如直接注入 EntityManagerInterface:

use Doctrine\ORM\EntityManagerInterface;

class YourCommand extends Command
{

    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        parent::__construct();
        $this->em = $em;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->em->persist($thing);
        $this->em->flush();
    }

}
Run Code Online (Sandbox Code Playgroud)


Blo*_*ops 12

最佳实践是将此任务委托给服务。参见以下示例:https : //symfony.com/doc/current/console.html#getting-services-from-the-service-container

但是,您也可以在命令中添加一个构造函数并为其提供ContainerInterface。那你就做$this->container->get('doctrine')->getManager();

// YourCommand.php

private $container;

public function __construct(ContainerInterface $container)
{
    parent::__construct();
    $this->container = $container;
}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $em = $this->container->get('doctrine')->getManager();

    // do stuff...
}
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记在脚本开始时添加正确的“ use”语句:

use Symfony\Component\DependencyInjection\ContainerInterface;
Run Code Online (Sandbox Code Playgroud)

  • 实际上,最好将实体管理器直接注入到构造函数中:“公共函数__construct(EntityManagerInterface $ entityManager)”,然后在与“ $ this-> entityManager”一起执行时直接使用它。 (5认同)

小智 -3

我使用这个语法:

    $em = $this->getContainer()->get('doctrine')->getEntityManager();
Run Code Online (Sandbox Code Playgroud)