Symfony: Redirect output of a Process
Asked Answered
B

1

5

I am upgrading an old Symfony application (v2.8) to Symfony 5.3. I am using the process component where the arguments have to be passed in another way than before.

My previous code was like

use Symfony\Component\Process\Process;

$cmd = sprintf('mysqldump mydatabase > %s', $outputTarget);
$process = new Process($cmd);
$process->run();

Now, Symfony's Process constructor expects the binary and the arguments to be passed as array (see here).

How can I achieve the output redirection with the new style?

$process = new Process(['mysqldump', 'mydatabase', '>', $outputTarget]);
$process->run();

Won't work, because the > would be escaped.

Behn answered 29/11, 2021 at 9:51 Comment(0)
B
8

I have found a workaround. Process::fromShellCommandline can be used to redirect the output. This is my solution:

$process = Process::fromShellCommandline('mysqldump mydatabase > "$OUTPUT_TARGET"');
$process->start(null, [
    'OUTPUT_TARGET' => $outputTarget,
]);

This way the arguments get passed as environment variables to the process and the OS (or the shell?) takes care about replacing the placeholders of the command by the env.

Behn answered 29/11, 2021 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.