New in Symfony 3.1: Input and Output Stream for Processes
April 7, 2016 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Output Streaming
In Symfony 3.1, the Process
class implements PHP's IteratorAggregate interface
to return an iterator to the output of the running process. The key of the
returned value is the type of output (Process::OUT
or Process::ERR
) and
the value is the output generated by the process.
This new feature allows to stream the output as easily as using a foreach()
construct:
1 2 3 4 5 6 7 8 9 10 11 12
use Symfony\Component\Process\Process;
$process = new Process('ls -lsa');
$process->start();
foreach ($process as $type => $data) {
if ($process::OUT === $type) {
echo $data."\n";
} else {
echo "[ERR] ".$data."\n";
}
}
Input Streaming
Similarly, the Process component has added in Symfony 3.1 a new InputStream
class to allow passing data to the standard input of a process while it's running.
Traditionally you used the setInput()
method to provide that information:
1 2 3 4 5
use Symfony\Component\Process\Process;
$process = new Process('cat');
$process->setInput('file.txt');
$process->run();
In this example, after the data has been fully written to the standard input of
the subprocess, the associated pipe is closed and you can't provide more input.
The new InputStream
overcomes that limitation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
use Symfony\Component\Process\InputStream;
$input = new InputStream();
$input->write('foo');
$process = new Process('my_script');
$process->setInput($input);
$process->start();
// ... read process output or do other things
$input->write('bar');
// ... read process output or do other things
$input->write('qux');
$input->close();
// ...
You can provide as many inputs as needed during the execution of the process.
The write()
method accepts scalars, stream resources or Traversable objects
as argument. When you are done writing to the standard input, just call to the
close()
method.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Is there an example use case for this?
@Philippe Villiers maybe an ftp client like sftp where you need to input commands while the program is running to interact with it.