symfony - 在灯具中执行 Symfony 4 自定义命令

标签 symfony process command locking fixtures

我的 symfony 项目中有一个自定义命令,用于使用应用程序在开发和生产环境中工作所需的默认数据填充数据库。

对于开发环境,我有一个依赖于这些默认公共(public)数据的 fixture 脚本。 我正在尝试在 fixture 脚本中调用我的自定义 Symfony 命令,以便确保拥有正确加载我的 fixture 所需的数据。

这是我在“伪脚本”中的自定义命令 app:db:populate,只是创建了一堆实体,persit & flush。当我通过 php bin/console app:db:populate

调用它时,我的自定义命令工作正常
protected function execute(InputInterface $input, OutputInterface $output)
{
    // Creating a bunch of default entities, persist them and flush

    $data = new MyDefaultEntity();
    // ...
    $this->manager->persist($data);
    // ...
    $this->manager->flush();
}

然后,在我的 fixture 脚本中,我想先调用 app:db:populate,因为 fixture 依赖于这些数据。所以我尝试使用 Process 类以这种方式执行我的脚本:

public function load(ObjectManager $manager)
{
    // Execute the custom command
    $cmd = 'php bin/console app:db:populate';
    $process = new Process($cmd);
    $process->run(function ($type, $buffer) {
        if (Process::ERR === $type) {
            echo 'ERR > '.$buffer;
        } else {
            echo 'OUT > '.$buffer;
        }
    });

    // Then load the fixtures !
    // ...
}

自定义命令似乎执行得很好,直到 $this->manager->flush();

我的控制台中出现以下错误(帖子的数据被混淆):

In AbstractMySQLDriver.php line 36:

  An exception occurred while executing 'INSERT INTO ....(..., ..., ...) VALUES (?, ?, ?)' with params ["...", "...", "..."]:

  SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction

对于这个错误,我不知道该怎么办...为什么在通过经典控制台调用使用命令时命令正常工作,为什么它在进程中不工作?

最佳答案

所以,简短的回答是

引用 Symfony 文档:

You may have the need to execute some function that is only available in a console command. Usually, you should refactor the command and move some logic into a service that can be reused in the controller.

我最终创建了一个处理所有 app:db:populate 逻辑的服务类(读取一个 json 文件并在数据库中插入基本的应用程序实体)。然后,我在 app:db:populate 执行方法和 AppFixtures 加载方法中调用此服务。

希望这会对某人有所帮助。

关于symfony - 在灯具中执行 Symfony 4 自定义命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60148354/

相关文章:

mysql - 如何使用MySQL管理服务器端进程

c# - 如何处理Process类返回的错误?

php - Symfony 2 Sonata Admin Bundle 的表演 Action 不起作用

php - 使用 ProxyQuery + where 子句进行内连接

process - VB6 如何检查进程 ID 是否已终止

python - 在 Python 3.4 中使用 input() 时出现 NameError

bash - 查找包含给定文件的目录?

linux - 可能是 grep,但仍然不知道如何读取 file1 中的行并将其粘贴为 file2 中的列

php - 我如何编辑带有附件的表单 [Symfony]

php - Symfony2 多对多复选框