【问题标题】:How to create new stream from Redis cache如何从 Redis 缓存创建新流
【发布时间】:2020-05-24 04:49:38
【问题描述】:

我将图像存储在 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 变量是该图像的字节数。如何将这些字节转换为流?

【问题讨论】:

  • 响应应该是Psr\Http\Message\ResponseInterface 的实例,$image 应该是Psr\Http\Message\StreamInterface 的实例。
  • 我理解错误,我的问题是如何将文本字符串转换为实际流?

标签: php slim psr-4 slim-4


【解决方案1】:

为了从字符串创建流,您可以使用 Slim 的 Psr\Http\Message\StreamFactoryInterface 实现(参见 PSR-17: HTTP Factories,或任何其他实现相同接口的外部库(如 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);

// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 2015-10-02
    • 2017-10-27
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多