Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3120

New in Symfony 3.1: Input and Output Stream for Processes

$
0
0
Nicolas Grekas

Contributed by
Nicolas Grekas
in #18386 and #18414.

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
useSymfony\Component\Process\Process;$process=newProcess('ls -lsa');$process->start();foreach($processas$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
useSymfony\Component\Process\Process;$process=newProcess('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
useSymfony\Component\Process\InputStream;$input=newInputStream();$input->write('foo');$process=newProcess('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 theclose() method.


Be trained by Symfony experts - 2016-04-08 Clichy - 2016-04-11 Cologne - 2016-04-11 Cologne

Viewing all articles
Browse latest Browse all 3120

Trending Articles