Skip to content
This repository has been archived by the owner on Jan 16, 2019. It is now read-only.

Stream interfaces

Frank Kleine edited this page Aug 3, 2014 · 3 revisions

Stream interfaces

Stubbles provides input and output streams for different kind of sources within the stubbles\streams package. All input streams implement the stubbles\streams\InputStream interface, all output streams the stubbles\streams\OutputStream interface. While input streams can be used to read data from a source, output streams can be used to write data to a certain source.

Interfaces and their methods

Input stream methods

The input stream interface provides the following methods:

  • read($length = 8192) - returns given amount of bytes
  • readLine($length = 8192) - returns all characters up to given length until next line break
  • bytesLeft() - returns the amount of bytes left to be read
  • eof() - checks whether end of input was reached
  • close() - closes the stream

Output stream methods

The output stream interface provides the following methods:

  • write($bytes) - writes given bytes and returns amount of written bytes
  • writeLine($bytes) - same as write(), but adds a line break at end of bytes
  • close() - closes the stream

Seekable streams

Some streams are seekable which means you can go from one position in the stream to another. Input streams which are seekable implement the stubbles\streams\Seekable interface. It provides the following methods:

  • seek($offset, $whence = Seekable::SET) - sets internal stream pointer to given position
  • tell() - returns the current position of the internal stream pointer

Decorating streams

Encoding-related streams

Sometimes it is necessary to decode input stream data into the internal encoding of the application. While Stubbles' internal encoding is UTF-8, all data read from input streams should be UTF-8 itself or at least converted to UTF-8 before returned from the input stream. To ease this, the stubbles\streams\DecodingInputStream class decorates another input stream given as first parameter on construction, and tries to decode the data read from the decorated input stream from the stream encoding to UTF-8 using iconv(). However you need to specify the charset of the decorated input stream as second parameter to the constructor:

$decodingInputStream = new DecodingInputStream($encodedInputStream, 'iso-8859-1');

Of course there must be a possibility to write back into the correct encoding. For this, the stubbles\streams\EncodingOutputStream class can be used. It tries to convert from internal UTF-8 into the encoding of the decorated output stream using iconv().

$encodingOutputStream = new EncodingOutputStream($encodedOutputStream, 'iso-8859-1');