Skip to content
Alex Kiesel edited this page Jun 7, 2012 · 7 revisions

I/O: Streams

Input

Input streams are defined by the io.streams.InputStream interface and provide methods for reading.

<?php
  $stream= ...;
  
  while ($stream->available()) {
    $chunk= $stream->read();
    // ...
  }
  
  $stream->close();
?>

Input stream implementations are io.streams.FileInputStream and io.streams.MemoryInputStream.

Output

Input streams are defined by the io.streams.OutputStream interface and provide methods for writing.

<?php
  $stream= ...;
  
  $stream->write($chunk1);
  $stream->write($chunk2);
  
  $stream->close();

?>

Output stream implementations are io.streams.MemoryOutputStream, io.streams.FileOutputStream and io.streams.ConsoleOutputStream.

Buffered streams

Stream aggregates that support buffering are io.streams.BufferedInputStream and io.streams.BufferedInputStream.

<?php
  $stream= new BufferedInputStream(new FileInputStream(...));
  while ($stream->available()) {
    $chunk= $stream->read();
    // ...
  }
  $stream->close();
?>

Seeking

Streams that supporting seeking implement the io.streams.Seekable interface.

Stream adapters

The io.streams.Streams class provides static methods to wrap stream objects into PHP file handles. This way, legacy APIs can be made to work with streams.

<?php
  // Reading
  $fi= Streams::readableFd(new MemoryInputStream('Hello'));
  $hello= fgets($fi, 1024);
  fclose($fi);
  
  // Writing
  $fd= Streams::writeableFd(new FileOutputStream(new File('out')));
  fwrite($fd, 'Contents');
  fclose($fd);
?>

History

The streams API was first introduced in xp-framework/rfc#88 - RFC 0088 - Streams API - in November 2006.