Symfony Process - execute command from service
Asked Answered
N

2

9

How can I run a command (app/console execute:my:command) in a service via new Process?

I try this:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process(
    'app/console execute:my:command'
);
$process->start();

But nothing happens ... If I call it manually via terminal it works:

app/console execute:my:command

What am I doing wrong?

EDIT - Solution: We need to write the whole path. In my case:

($this->kernelRootDir is : %kernel.root_dir%)
$processString = sprintf(
    'php %s/../app/console %s %s',
    $this->kernelRootDir,
    self::MY_COMMAND,
    $myArgument
);

$process = new Process($processString);
$process->start();

if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}
Numen answered 23/3, 2017 at 9:54 Comment(1)
Have you tried to add path to PHP cli behind app/console ?Norry
H
12

This is pretty much all you need to do really. I always set the working directory and assume this is needed so that the Symfony command is run from the root of the project

$process = new Process(
    'app/console execute:my:command'
);
$process->setWorkingDirectory(getcwd() . "../");

$process->start();

For debugging purposes I generally set

$process->setOptions(['suppress_errors' => false]);

as well

Hornswoggle answered 23/3, 2017 at 10:5 Comment(0)
A
1

I can't get the setWorkingDirectory function to work properly on Windows...

The fromShellCommandline function works better for me on Windows with Symfony >= 4.4:

$cmd = sprintf('php %s/bin/console %s', 
    $this->getParameter('kernel.project_dir'), 
    'app:my:command'
);

Process::fromShellCommandline($cmd)->run();

Hope this will help someone else!

Almonry answered 21/2, 2023 at 0:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.