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)
我猜测当前工作目录与您的项目根目录不匹配。因此,相对路径bin/console不存在。
您有两种方法可以解决此问题:
设置当前工作目录:
$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)通过 Symfony Command 调用来调用命令,官方文档文章中有描述
请记住,#2 有轻微的开销(如文章中所述)
希望这可以帮助...