我正在构建一个通读图像缓存,并且正在寻找一种将 PSR-7 流写入服务器上的文件的方法。该文档对于如何执行此操作并不是非常清楚(它主要关注于提供文件,而不是编写文件)。
我目前最大的努力使用的$stream->detach()是不理想的(因为它破坏了底层流,然后我无法将其返回给用户)。有一个更好的方法吗?
/* @var GuzzleHttp\Client $httpClient */
$response = $httpClient->request(
'GET', 'https://example.com/image.png'
);
// Validate response, etc.
$stream = $response->getBody();
$stream->isReadable(); // now true
$cachePath = '/path/to/local/cache/unique-name.png';
$writeHandle = fopen($cachePath, 'w');
stream_copy_to_stream($stream->detach(), $writeHandle);
$stream->isReadable(); // now false due to detach()
// To serve the data I'd need to create a new stream
// from the image I've just created
return new GuzzleHttp\Psr7\Stream(fopen($cachePath, 'rb'))
Run Code Online (Sandbox Code Playgroud)
抢先解决所有“你为什么要这样做”的问题;我从远程服务获取这些图像。该服务的条款要求我在本地缓存图像。