如何从 Redis 缓存创建新流

How to create new stream from Redis cache

我正在将图像存储在 redis 中。

$image = $cache->remember($key, null, function () use ($request, $args) {
            $image = $this->get('image');
            $storage = $this->get('storage');

            return $image->load($storage->get($args['path'])->read())
                        ->withFilters($request->getQueryParams())
                        ->stream();
        });

并试图取回它:

return (new Response())
                ->withHeader('Content-Type', 'image/png')
                ->withBody($image);

它给我这个错误:

Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() 
must implement interface Psr\Http\Message\ResponseInterface, string returned

$image 变量是该图像的字节。如何将这些字节转换为流?

为了从字符串创建流,您可以使用 Slim 的 Psr\Http\Message\StreamFactoryInterface 实现(参见 PSR-17: HTTP Factories, or any other external library implementing the same interface (like laminas-diactoros)。

使用Slim库,应该是这样的:

<?php

use Slim\Psr7\Response;
use Slim\Psr7\Factory\StreamFactory;

// The string to create a stream from.
$image = $cache->remember($key, null, function () use ($request, $args) {
    //...
});

// Create the stream factory.
$streamFactory = new StreamFactory();

// Create a stream from the provided string.
$stream = $streamFactory->createStream($image);

// Create a response.
$response = (new Response())
                ->withHeader('Content-Type', 'image/png')
                ->withBody($stream);

// Do whatever with the response.

或者,您可以使用方法 StreamFactory::createStreamFromFile:

<?php

// ...

/*
 * Create a stream with read-write access:
 *
 *  'r+': Open for reading and writing; place the file pointer at the beginning of the file.
 *  'b': Force to binary mode.
 */
$stream = $streamFactory->createStreamFromFile('php://temp', 'r+b');

// Write the string to the stream.
$stream->write($image);

// ...