gpt4 book ai didi

php - 交响乐 4 : doctrine in command

转载 作者:可可西里 更新时间:2023-10-31 23:58:05 28 4
gpt4 key购买 nike

我正在使用 symfony 4,如果我在 Command 类中,我想访问一个实体的存储库。没有函数 getDoctrine 或其他东西..

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

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

最佳答案

最佳做法是将此任务委托(delegate)给服务。请参阅此示例: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...
}

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

use Symfony\Component\DependencyInjection\ContainerInterface;

关于php - 交响乐 4 : doctrine in command,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48234418/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com