【问题标题】:Symfony3.4 custom commandSymfony3.4 自定义命令
【发布时间】:2020-01-22 15:44:30
【问题描述】:

我正在尝试创建一个个人命令来更改我的数据库中的数据。我可以直接用“SELECT *”来做......但是Symfony说好的方法是创建一个命令来应用数据库等的更改......所以这就是我面临的问题:

当我覆盖默认的 __construct 方法时,Symfony 不会自动注册命令,这意味着 Symfony 只是忽略它。当我删除构造函数时,我的命令有效,但我只是从我的 $entitymanager 中得到 null (这是逻辑,因为我没有将任何东西放入 entitymanager ?)。

请问有人可以帮我解决吗?对不起我的英语不好,谢谢你的帮助:)

So here is my code for the command

【问题讨论】:

  • 不要在提问中使用图片。只需复制/粘贴到您的构造函数代码中。我怀疑你没有调用父构造函数。按照文档中的示例进行操作。

标签: symfony command


【解决方案1】:
Here another alternative to use entityManager in your 3.4 since autowiring is not as good as 4.0 and above 
`class CreateUserCommand extends ContainerAwareCommand
{
 protected function execute(InputInterface $input, OutputInterface $output)
    {
        $entityManager = $this->getContainer()->get('doctrine')->getManager(); 
    }
}
`

【讨论】:

  • 谢谢你,我现在有另一个问题:我遇到了一个致命错误,即“可捕获的致命错误:Doctrine\ORM\EntityManager 类的对象无法转换为字符串”我会尝试在互联网上找到它
  • 好的,我刚刚发现了我使用这个的问题:“$applications = $this->$entityManager->getRepository('Corsaire4Bundle:Application')->findAll();”解决方案是删除 $this
  • 如果您觉得我的回答有用,请标记为已解决
【解决方案2】:

Symfony 的版本?

但是尝试这样做:

use Symfony\Component\Console\Command\Command;
[...]

class CreateUserCommand extends Command
{
    protected static $defaultName = 'app:create-user';

    /**
    * @var EntityManager
     */
    private $entityManager;

    public function __construct(
        EntityManager $entityManager,
        string $name = null
    ) {
    parent::__construct($name);
    $this->entityManager = $entityManager;

    protected function configure()
    {
        parent::configure();
        [...]
    }

        protected function execute(InputInterface $input, OutputInterface $output)
    {
        [...]
    }

}

【讨论】:

  • 不工作,我在 Symfony 3.4 上,因为应用程序太旧了。
  • 类扩展了什么?
  • 这是我的班级名称和扩展:“class ResetPmStatusCommand extends Command”所以我的班级正在扩展命令
【解决方案3】:

您需要自动装配 EntityManagerInterface $entityManager 而不是 EntityManager 并确保启用自动装配,如果不需要,您需要在 service.yml 中手动进行

【讨论】:

  • 谢谢你的回答,我的自动装配在 app/config/services.yml 中设置为“true”。我尝试了 EntityManagerInterface 但它仍然无法正常工作。 :(
  • 你确定你没有在自动装配中排除 Command 吗?
  • 我不这么认为,我在 services.yml 中没有告诉在自动装配中排除命令。有没有办法检查?
【解决方案4】:

parent::__construct 应该始终是第一行。

移动这条线,它应该可以正常工作。

{
    parent::__construct();    
    $this->entityManager = $entityManager;
}

【讨论】:

  • 你试过了吗?这两行的顺序没有区别。
  • 是的,我试过了,当然,它改变了一些东西。当父调用之前,你初始化所有你需要的依赖(比如命令注册等)。
  • 您好,谢谢您的回答。可悲的是它不起作用,我的命令仍然被忽略:(。
猜你喜欢
  • 2014-03-17
  • 2010-12-15
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多