Streams, blobs, and binary data
HTTP bodies are ultimately just streams of bytes. Sometimes we treat them as text, but underneath they still travel as raw data.
This package includes a few classes that help at different levels:
Streamfor PSR-7 body streamsBlobfor binary or textual body chunksFilefor file-like blob data with a filenameArrayBufferfor byte-oriented buffer data
Stream
GT\Http\Stream is the PSR-7 stream implementation used by requests and responses.
use GT\Http\Stream;
$stream = new Stream("php://memory");
$stream->write("Hello");
$stream->rewind();
echo $stream->getContents();
Common methods include:
write()read()getContents()rewind()seek()tell()eof()getSize()
In everyday use, the most common place you will meet it is through:
$request->getBody();
$response->getBody();
Blob
Blob collects one or more string-like parts into a single object with:
sizetype- string casting through
__toString()
use GT\Http\Blob;
$blob = new Blob(
["Hello", " ", "world"],
["type" => "text/plain"]
);
echo $blob; // Hello world
echo $blob->size; // 11
echo $blob->type; // text/plain
File
File extends Blob and adds a name.
You can build it from an array of parts, or from an SplFileObject.
use GT\Http\File;
use SplFileObject;
$file = new File(
new SplFileObject("avatar.png"),
"avatar.png"
);
This makes it useful for FormData values and file-style payload handling.
ArrayBuffer
ArrayBuffer is a fixed-size buffer of bytes.
It is returned by Response::arrayBuffer() and awaitArrayBuffer().
$buffer = $response->awaitArrayBuffer();
echo $buffer->byteLength;
For most application code, Blob and plain text are easier to work with, but ArrayBuffer is useful when you need a byte-oriented representation.
Response body conversions
Response provides several helpers that convert the body stream into other object types:
awaitText()awaitJson()awaitBlob()awaitArrayBuffer()awaitFormData()
This means the same underlying response body can be consumed in the format that best fits the task.
The incoming request also carries server-level metadata around it, which is covered in ServerInfo and request metadata.