drewlabs/psr7-stream
提供PSR7流接口的实用类和实现
v2.0.2
2023-09-28 15:32 UTC
Requires
- php: >=7.2
- psr/http-factory: ^1.0
- psr/http-message: ^2.0
Requires (Dev)
- phpunit/phpunit: >=6.0
README
提供PSR7 Stream和StreamFactory接口的实现
用法
- 创建Psr7 Stream
// ... use Drewlabs\Psr7Stream\Stream; // ... // Creates PHP built-in streams such as php://memory and php://temp $stream = Stream::new('', 'wb+');
- 流工厂
- 从PHP资源创建Psr7 Stream
// ... use Drewlabs\Psr7Stream\StreamFactory; // ... // Create a PSR7 stream factory instance $factory = new StreamFactory(); // Creates stream from resources $stream = $factory->createStreamFromResource(fopen(__DIR__ . '/../../examples/test.txt', 'rb'));
- 从文件路径创建Psr7 Stream
// ... use Drewlabs\Psr7Stream\StreamFactory; // ... // Create a PSR7 stream factory instance $factory = new StreamFactory(); // Creates stream from path $stream = $factory->createStreamFromFile(__DIR__ . '/../../examples/test.txt');
+v1.2x
从v1.2.x版本开始,添加了堆叠流实现和懒流实现。
- 堆叠流
堆叠流是对流接口的抽象,使用连续内存(数组)创建了一个StreamInterface
实例的堆栈,并为整个组提供相同的流接口API。对于像close()
、detach()
、read()
、getSize()
等操作,每个项目将按插入的顺序进行访问。
创建堆叠流
use Drewlabs\Psr7Stream\StreamFactory as Factory; $stream = Factory::stack(); // TO initialize the instance at contruction time // The stream instance is initialized with 2 chunks $stream = Factory::stack(Stream::new(''), Stream::new(__DIR__ . '/vendor/autoload.php'))
注意 堆叠流提供了两个额外的用于添加和删除元素的方法。
向堆栈中添加新的流
use Drewlabs\Psr7Stream\StreamFactory as Factory; $stream = Factory::stack(); // Add a new stream instance $stream->push(Stream::new('/path/to/resource'));
移除最后插入的堆栈
use Drewlabs\Psr7Stream\StreamFactory as Factory; $stream = Factory::stack(); // Pop the last stream from the stack and return it $s = $stream->pop();
警告 使用pop()
方法时请小心,因为它会将流内部的指针重置,以避免数据损坏。
- 懒流
懒流是一个简单的流对象的抽象,只有在开发者准备好进行操作(如read()
、write()
等)时才会解析流。它提供了一个懒创建的PSR7 StreamInterface
实例实现。
可以通过传递一个可调用来构造方法创建懒流
use Drewlabs\Psr7Stream\StreamFactory as Factory; use Drewlabs\Psr7Stream\Stream; use Drewlabs\Psr7Stream\LazyStream; // $stream_source = 'Hello world...'; $stream = Factory::lazy(function() use (&$stream_source) { return Stream::new($stream_source); }); // Or using constructor $stream = new LazyStream(function() use (&$stream_source) { return Stream::new($stream_source); });
或使用CreatesStream
接口的实例,它提供了一个面向对象的方式来创建新的流
use Drewlabs\Psr7Stream\CreatesStream; use Drewlabs\Psr7Stream\Stream; // CreateTextStream.php class CreateTextStream implements CreatesStream { /** * * @var string * */ private $source; public function __construct($source) { $this->source = $source; } public function createStream() { return Stream::new($this->source); } } // main.php $stream = new LazyStream(new CreateTextStream('/path/to/resource')); // Or using factory function $stream = Factory::lazy(new CreateTextStream('/path/to/resource'));