Symfony4 - 进程 - 命令无法打开输入文件 bin/console

Bor*_*éec 1 php command-line-interface symfony

我正在构建一个 symfony4 网络应用程序。我有一个命令,可以像魅力一样直接在 cli 中运行:

php bin/console app:analysis-file 4
Run Code Online (Sandbox Code Playgroud)

但是当我尝试exec直接从Controllervia 进行操作时:

$process = new Process('php bin/console app:analysis-file '. 
$bankStatement->getId());
$process->run();
Run Code Online (Sandbox Code Playgroud)

然后$process->getOutput()返回“ Could not open input file bin/console”。

这是Command Class

class AnalysisFileCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('app:analysis-file')
            ->addArgument('file_id', InputArgument::REQUIRED);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $entityManager = $this->getContainer()->get('doctrine')->getEntityManager();
        $bankStatement = $entityManager->getRepository(BankStatement::class)->find($input->getArgument("file_id"));
        $bankStatement->setStatus(BankStatement::ANALYZING);
        $entityManager->persist($bankStatement);
        $entityManager->flush();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jov*_*vic 6

我猜测当前工作目录与您的项目根目录不匹配。因此,相对路径bin/console不存在。

您有两种方法可以解决此问题:

  1. 设置当前工作目录:

    $kernel = ...; // Get instance of your Kernel
    $process = new Process('php bin/console app:analysis-file ');
    $process->setWorkingDirectory($kernel->getProjectDir());
    $bankStatement->getId());
    $process->run();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 通过 Symfony Command 调用来调用命令,官方文档文章中有描述

请记住,#2 有轻微的开销(如文章中所述)

希望这可以帮助...

  • 啊啊啊啊……效果很好。可惜我忘记了工作目录。无论如何,对于那些寻找如何获取内核实例的人:`$this->container->get('kernel');` 谢谢! (2认同)