yuloh / stream
PSR-7 的流实现
Requires
- php: ~5.5|~7.0
- psr/http-message: ^1.0
Requires (Dev)
- guzzlehttp/psr7: ^1.3
- php-mock/php-mock: ^1.0
- phpunit/phpunit: 4.*
- scrutinizer/ocular: ~1.3
- slim/slim: ^3.4
- squizlabs/php_codesniffer: ~2.3
- zendframework/zend-diactoros: ^1.3
This package is auto-updated.
Last update: 2022-02-01 12:58:20 UTC
README
PSR-7 流实现。
简介
此包为 PSR-7 提供了 Psr\Http\Message\StreamInterface
的实现。有时候你可能只需要一个流,但不想依赖整个 PSR-7 实现。
假设你正在编写一个 PSR-7 中间件,并且需要设置一个新的响应体。
如果你尝试使用 $response->getBody()->write()
写入数据,可能已经存在一个比你要写入的更长的现有体。唯一能让这工作方法是向字符串末尾写入填充,这并不是理想的做法。
创建新响应体的唯一方法是实例化一个流。一个很好的方法是要求一个工厂对象作为依赖项,并使用它来创建流。缺点是你为用户添加了另一个设置步骤,用户需要配置。
此包允许你提供一个默认实现,因此你的中间件可以在不设置流工厂的情况下工作。由于它是一个单独的包,你不需要为了流而拉入整个 PSR-7 实现,并且你不会与用户的 PSR-7 实现产生依赖冲突。
它还包括所有常见 PSR-7 实现的接口和适配器,因此用户不需要手动设置。
安装
通过 Composer
$ composer require yuloh/stream
用法
工厂
使用此包最简单的方法是使用 StreamFactory
。create
方法将从标量、字符串、资源或对象(如果实现 JsonSerializable 或 __toString)创建一个 Stream
。
$stream = (new StreamFactory())->create('Hello world!');
构造函数
你也可以直接创建一个流。你需要为构造函数提供有效的 资源 作为唯一参数。
use Yuloh\Stream\Stream; $resource = fopen('php://temp', 'r+'); $stream = new Stream($resource);
允许不同的实现
为了允许用户使用他们自己的流,你应该对 StreamFactoryInterface
进行类型提示,而不是使用具体的实现。此包包含所有常见实现的适配器,因此用户可以轻松使用他们自己的流。
use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Yuloh\Stream\StreamFactoryInterface; use Yuloh\Stream\StreamFactory; class HelloMiddleware { public function __construct(StreamFactoryInterface $streamFactory = null) { $this->streamFactory = $streamFactory ?: new StreamFactory(); } public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { $stream = $this->streamFactory->create('Hello world!'); $response = $response->withBody($stream); return $next($request, $response); } }
use Yuloh\Stream\Adapters; // Usage with default implementation: new HelloMiddleware(); // Usage with Zend Diactoros: new HelloMiddleware(new Adapters\DiactorosStreamFactory()); // Usage with Guzzle PSR7: new HelloMiddleware(new Adapters\GuzzleStreamFactory()); // Usage With Slim Framework: new HelloMiddleware(new Adapters\SlimStreamFactory());
测试
$ composer test
许可
MIT 许可证 (MIT)。请参阅 许可文件 以获取更多信息。