You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PHP Laminas中实现Redis缓存遇到配置问题求助

解决Laminas Redis缓存服务配置问题

核心问题:你的工厂直接将配置数组传给RedisCacheService的构造函数,但该类期望接收StorageInterface实例,这是错误的根源。以下是修正方案:

1. 修正RedisCacheServiceFactory工厂类

利用Laminas\Cache\CacheFactory根据配置生成符合StorageInterface的Redis缓存实例,代码如下:

use Laminas\Cache\CacheFactory;
use Laminas\Cache\Storage\StorageInterface;
use Psr\Container\ContainerInterface;
use Laminas\ServiceManager\Factory\FactoryInterface;

class RedisCacheServiceFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): RedisCacheService
    {
        $config = $container->get('config');
        $cacheConfig = $config['redis-cache'];
        
        // 通过CacheFactory生成StorageInterface实例
        $cacheStorage = CacheFactory::factory($cacheConfig);
        
        return new RedisCacheService($cacheStorage);
    }
}

2. 确认RedisCacheService类定义

你的RedisCacheService类构造函数类型声明正确,只需保证工厂传入的是StorageInterface实例即可,可按需添加缓存操作方法:

use Laminas\Cache\Storage\StorageInterface;

class RedisCacheService
{
    public function __construct(private StorageInterface $cacheStorage)
    {
    }

    // 示例:添加缓存写入方法
    public function setItem(string $key, mixed $value): bool
    {
        return $this->cacheStorage->setItem($key, $value);
    }

    // 示例:添加缓存读取方法
    public function getItem(string $key): mixed
    {
        $success = false;
        $item = $this->cacheStorage->getItem($key, $success);
        return $success ? $item : null;
    }
}

3. 注册服务到服务管理器

在应用配置文件(如config/services.php)中注册服务与工厂:

return [
    'factories' => [
        RedisCacheService::class => RedisCacheServiceFactory::class,
    ],
];

注意事项

  • CacheFactory::factory()会自动根据配置中的适配器名称实例化Redis适配器,并加载配置的插件(如exception_handler)。
  • 确保redis.local.php已被纳入应用配置合并流程,保证$container->get('config')能读取到redis-cache配置项。

内容的提问来源于stack exchange,提问作者user27601930

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:22:46