• Stars
    star
    357
  • Rank 114,882 (Top 3 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 7 years ago
  • Updated 22 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A non-blocking stream abstraction for PHP based on Amp.

amphp/byte-stream

AMPHP is a collection of event-driven libraries for PHP designed with fibers and concurrency in mind. amphp/byte-stream specifically provides a stream abstraction to ease working with various byte streams.

Installation

This package can be installed as a Composer dependency.

composer require amphp/byte-stream

Requirements

This package requires PHP 8.1 or later.

Usage

Streams are an abstraction over ordered sequences of bytes. This package provides the fundamental interfaces ReadableStream and WritableStream.

Note Previous versions used the terms InputStream and OutputStream, but these terms can be confusing depending on the use case.

ReadableStream

ReadableStream offers a primary method: read(). It returns a string or null. null indicates that the stream has ended.

The following example shows a ReadableStream consumption that buffers the complete stream contents.

$stream = ...;
$buffer = "";

while (($chunk = $stream->read()) !== null) {
    $buffer .= $chunk;
}

// do something with $buffer

Note Amp\ByteStream\buffer($stream) can be used instead, but we'd like to demonstrate manual consumption here.

This package offers some basic implementations, other libraries might provide even more implementations, such as amphp/socket.

Payload

Payload implements ReadableStream while also providing a buffer() method for buffering the entire contents. This allows consuming a message either in chunks (streaming) or consume everything at once (buffering). When the object is destructed, any remaining data in the stream is automatically consumed and discarded. This class is useful for small payloads or when the entire contents of a stream is needed before any processing can be done.

Buffering

Buffering a complete readable stream can be accomplished using the buffer() method.

$payload = new Payload($inputStream);
$content = $payload->buffer();

Streaming

Sometimes it's useful / possible to consume a payload in chunks rather than first buffering it completely, e.g. streaming a large HTTP response body directly to disk.

while (null !== $chunk = $payload->read()) {
    // Use $chunk here, works just like any other ReadableStream
}

ReadableBuffer

An ReadableBuffer allows creating a ReadableStream from a single known string chunk. This is helpful if the complete stream contents are already known.

$stream = new ReadableBuffer("foobar");

It also allows creating a stream without any chunks by passing null as chunk / omitting the constructor argument:

$stream = new ReadableBuffer;

// The stream ends immediately
assert(null === $stream->read());

ReadableIterableStream

ReadableIterableStream allows converting an iterable that yields strings into a ReadableStream:

$inputStream = new Amp\ByteStream\ReadableIterableStream((function () {
    for ($i = 0; $i < 10; $i++) {
        Amp\delay(1);
        yield $emit(".");
    }
})());

ReadableResourceStream

This package abstracts PHP's stream resources with ReadableResourceStream and WritableResourceStream. They automatically set the passed resource to non-blocking mode and allow reading and writing like any other ReadableStream / WritableStream. They also handle backpressure automatically by disabling the read watcher in case there's no read request and only activate a writability watcher if the underlying write buffer is already full, which makes them very efficient.

DecompressingReadableStream

This package implements compression based on Zlib. CompressingWritableStream can be used for compression, while DecompressingReadableStream can be used for decompression. Both can simply wrap an existing stream to apply them. Both accept an $encoding and $options parameter in their constructor.

$readableStream = new ReadableResourceStream(STDIN);
$decompressingReadableStream = new DecompressingReadableStream($readableStream, \ZLIB_ENCODING_GZIP);

while (null !== $chunk = $decompressingReadableStream) {
    print $chunk;
}

See also: ./examples/gzip-decompress.php

WritableStream

WritableStream offers two primary methods: write() and end().

WritableStream::write

write() writes the given string to the stream. Waiting for completion allows writing only as fast as the underlying stream can write and potentially send over a network. TCP streams will return immediately as long as the write buffer isn't full.

The writing order is always ensured, even if the writer doesn't wait for completion before issuing another write.

WritableStream::end

end() marks the stream as ended. TCP streams might close the underlying stream for writing, but MUST NOT close it. Instead, all resources should be freed and actual resource handles be closed by PHP's garbage collection process.

The following example uses the previous example to read from a stream and writes all data to a WritableStream:

$readableStream = ...;
$writableStream = ...;
$buffer = "";

while (($chunk = $readableStream->read()) !== null) {
    $writableStream->write($chunk);
}

$writableStream->end();

Note Amp\ByteStream\pipe($readableStream, $writableStream) can be used instead, but we'd like to demonstrate manual consumption / writing here.

This package offers some basic implementations, other libraries might provide even more implementations, such as amphp/socket.

WritableResourceStream

This package abstracts PHP's stream resources with ReadableResourceStream and WritableResourceStream. They automatically set the passed resource to non-blocking mode and allow reading and writing like any other ReadableStream / WritableStream. They also handle backpressure automatically by disabling the read watcher in case there's no read request and only activate a writability watcher if the underlying write buffer is already full, which makes them very efficient.

CompressingWritableStream

This package implements compression based on Zlib. CompressingWritableStream can be used for compression, while DecompressingReadableStream can be used for decompression. Both can simply wrap an existing stream to apply them. Both accept an $encoding and $options parameter in their constructor.

$writableStream = new WritableResourceStream(STDOUT);
$compressedWritableStream = new CompressingWritableStream($writableStream, \ZLIB_ENCODING_GZIP);

for ($i = 0; $i < 100; $i++) {
    $compressedWritableStream->write(bin2hex(random_bytes(32));
}

$compressedWritableStream->end();

See also: ./examples/gzip-compress.php

Versioning

amphp/byte-stream follows the semver semantic versioning specification like all other amphp packages.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

The MIT License (MIT). Please see LICENSE for more information.

More Repositories

1

amp

A non-blocking concurrency framework for PHP applications. 🐘
PHP
4,135
star
2

http-server

An advanced async HTTP server library for PHP, perfect for real-time apps and APIs with high concurrency demands.
PHP
1,276
star
3

parallel

An advanced parallelization library for PHP, enabling efficient multitasking, optimizing resource use, and application responsiveness through multiple CPU threads.
PHP
745
star
4

http-client

An advanced async HTTP client library for PHP, enabling efficient, non-blocking, and concurrent requests and responses.
PHP
695
star
5

mysql

An async MySQL client for PHP, optimizing database interactions with efficient non-blocking capabilities. Perfect for responsive, high-performance applications.
PHP
346
star
6

thread

Unmaintained. Use https://github.com/amphp/parallel.
PHP
297
star
7

parallel-functions

Simplified parallel processing for PHP based on Amp.
PHP
264
star
8

ext-fiber

PHP Fiber extension
Assembly
238
star
9

process

An async process dispatcher for Amp.
PHP
225
star
10

socket

Non-blocking socket and TLS functionality for PHP based on Amp.
PHP
214
star
11

ext-uv

C
186
star
12

sync

Non-blocking synchronization primitives for PHP based on Amp and Revolt.
PHP
155
star
13

dns

Async DNS resolution for PHP based on Amp.
PHP
149
star
14

redis

Efficient asynchronous communication with Redis servers, enabling scalable and responsive data storage and retrieval.
PHP
146
star
15

websocket-client

Async WebSocket client for PHP based on Amp.
PHP
138
star
16

parser

A generator parser to make streaming parsers simple.
PHP
121
star
17

websocket-server

WebSocket component for PHP based on the Amp HTTP server.
PHP
112
star
18

serialization

Serialization tools for IPC and data storage in PHP.
PHP
105
star
19

cache

A fiber-aware cache API based on Amp and Revolt.
PHP
95
star
20

windows-registry

Windows Registry Reader.
PHP
92
star
21

file

An abstraction layer and non-blocking file access solution that keeps your application responsive.
PHP
90
star
22

hpack

HPack - HTTP/2 header compression implementation in PHP.
PHP
90
star
23

postgres

Async Postgres client for PHP based on Amp.
PHP
88
star
24

http

HTTP primitives which can be shared by servers and clients.
PHP
87
star
25

beanstalk

Asynchronous Beanstalk Client for PHP.
PHP
63
star
26

cluster

Building multi-core network applications with PHP.
PHP
56
star
27

aerys

A non-blocking HTTP application, WebSocket and file server for PHP based on Amp.
PHP
52
star
28

pipeline

Concurrent iterators and pipeline operations.
PHP
43
star
29

http-server-router

A router for Amp's HTTP Server.
PHP
37
star
30

green-thread

PHP
37
star
31

getting-started

A getting started guide for Amp.
PHP
36
star
32

websocket

Shared code for websocket servers and clients.
PHP
34
star
33

ssh

Async SSH client for PHP based on Amp.
PHP
33
star
34

injector

A recursive dependency injector used to bootstrap and wire together S.O.L.I.D., object-oriented PHP applications.
PHP
32
star
35

log

Non-blocking logging for PHP based on Amp and Monolog.
PHP
31
star
36

uri

Uri Parser and Resolver.
PHP
24
star
37

amphp.github.io

Main website repository.
HTML
23
star
38

react-adapter

Makes any ReactPHP library compatible with Amp.
PHP
23
star
39

artax

An async HTTP/1.1 client for PHP based on Amp.
PHP
21
star
40

phpunit-util

Helper package to ease testing with PHPUnit.
PHP
21
star
41

http-server-static-content

An HTTP server plugin to serve static files like HTML, CSS, JavaScript, and images effortlessly.
PHP
21
star
42

http-server-session

An HTTP server plugin that simplifies session management for your applications. Effortlessly handle user sessions, securely managing data across requests.
PHP
17
star
43

mysql-dbal

PHP
16
star
44

http-server-form-parser

An HTTP server plugin that simplifies form data handling. Effortlessly parse incoming form submissions and extracting its data.
HTML
16
star
45

stomp

A non-blocking STOMP client built on the amp concurrency framework
PHP
15
star
46

aerys-reverse

Reverse HTTP proxy handler for Aerys
PHP
15
star
47

sql

Common interfaces for Amp based SQL drivers.
PHP
14
star
48

loop

Discontinued. Merged into https://github.com/amphp/amp.
PHP
12
star
49

http-tunnel

This package provides an HTTP CONNECT tunnel for PHP based on Amp.
PHP
11
star
50

http-client-cookies

Automatic cookie handling for Amp's HTTP client.
PHP
10
star
51

rpc

Remote procedure calls for PHP based on Amp.
PHP
9
star
52

http-client-psr7

PSR-7 adapter for amphp/http-client.
PHP
8
star
53

http-client-cache

An async HTTP cache for Amp's HTTP client.
PHP
7
star
54

sql-common

Implementations shared by amphp/postgres and amphp/mysql
PHP
7
star
55

php-cs-fixer-config

Common code style configuration for all @amphp projects.
PHP
6
star
56

react-stream-adapter

Adapters to make React's and Amp's streams compatible.
PHP
6
star
57

windows-process-wrapper

Child process wrapper to support non-blocking process pipes on Windows.
C
5
star
58

amphp.org

Documentation for AMPHP v3 based libraries.
HTML
5
star
59

quic

PHP
4
star
60

logo

Repository to store the logo and other assets.
3
star
61

dbus

A non-blocking DBus Connector with message serialization based on Amp.
PHP
2
star
62

website-tools

Website administration tools for amphp.org.
PHP
1
star
63

template

This repository serves as template for new amphp projects.
1
star
64

website-shared

Unmaintained. Has been merged into https://github.com/amphp/amphp.github.io.
1
star
65

.github

1
star