Streams allow you to read and write data in a memory-efficient way. PHP has built-in support for streams, but the syntax is clunky, and it requires a bit of boilerplate code to work with. Aphiria wraps PHP's streaming functionality into a simple interface: Aphiria\IO\Streams\IStream
. Creating a stream is easy.
use Aphiria\IO\Streams\Stream;
$stream = new Stream(fopen('path/to/file', 'r+b'));
You can read chunks of data from a stream via
// Read 64 bytes from the stream
$stream->read(64);
You can also read to the end of a stream via
$stream->readToEnd();
Note: This will read to the end of the stream from the current cursor position. To read the entire stream from the beginning, use
(string)$stream
.
To write to a stream, call
$stream->write('foo');
To seek to a specific point in the stream, call
// Seek to the 1024th byte
$stream->seek(1024);
To rewind to the beginning, you can call
$stream->rewind();
To get the length of a stream, call
$stream->length;
If it is not knowable, then length
will return null
.
Note: If you happen to know the length of the stream ahead of time, you can pass it into the constructor, eg
new Stream(fopen('path/to/file', 'r+b'), 2056)
. If you write anything to the stream, then the length is recalculated.
Sometimes, you'll need to copy one stream to another. One example would be writing a response body's stream to the php://output
stream. You can do this via
$destinationStream = new Stream(fopen('php://output', 'r+b'));
$sourceStream = new Stream(fopen('path/to/file', 'r+b'));
$sourceStream->copyToStream($destinationStream);
Note: Copying to a stream does not rewind the source or destination streams. If you want to write the entire source stream to the destination, then call
$sourceStream->rewind()
prior to$sourceStream->copyToStream()
.
You can close a stream via
$stream->close();
Note: When PHP performs garbage collection,
close()
is automatically called by the destructor.
In some cases, such as multi-part requests, you may need to append multiple streams together, yet treat them like a single stream. This is where MultiStream
comes in handy:
use Aphiria\IO\Streams\MultiStream;
use Aphiria\IO\Streams\Stream;
$stream1 = new Stream('php://temp', 'r+b');
$stream1->write('foo');
$stream2 = new Stream('php://temp', 'r+b');
$stream2->write('bar');
$multiStream = new MultiStream();
$multiStream->addStream($stream1);
$multiStream->addStream($stream2);
echo (string)$multiStream; // "foobar"