我在让Redis缓存在ZF3应用程序中工作时遇到问题。
我一直在尝试通过各种网站(包括SO)拼凑出如何执行此操作的方法,但我不确定我是否对此采取了正确的方法。
到目前为止,我正在做什么:
在我的global.php配置文件中,添加了:
...
'redis_cache' => [
'adapter' => [
'name' => 'redis',
'options' => [
'server' => [
'host' => '127.0.0.1',
'port' => 6379,
]
]
],
]
...
我的控制器中有
use Zend\Cache\StorageFactory;
,然后在一种方法中,我尝试使用
$redis = StorageFactory::factory ($this->config['redis_cache']);
if ($redis->hasItem ('mykey'))
{
$value = $redis->getItem('mykey');
}
echo 'value = ' . $value;
这没有得到价值。但是,如果我在$ redis上执行print_r(),则可以看到Redis对象已创建。
答案 0 :(得分:0)
万一对其他人有帮助,这就是我找到的解决方法。
首先,我需要安装zend-serializer,我已经安装了zend-cache。
php composer require zendframework/zend-serializer
然后在我添加的/config/autoload/global.php中
'caches' => [
'RedisCache' => [
'adapter' => [
'name' => Redis::class,
'options' => [
'server' => [
'host' => '127.0.0.1',
'port' => '6379',
],
],
],
'plugins' => [
[
'name' => 'serializer',
'options' => [
],
],
],
],
],
在我添加的/config/application.config.php中
'service_manager' => [
'factories' => [
\Zend\Cache\Storage\Adapter\Redis::class => InvokableFactory::class
]
]
最后,在我的控制器工厂中,我像这样设置了依赖项注入
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$cache = $container->get('RedisCache');
return new IndexController($cache);
}
要在控制器中使用缓存,我将缓存添加到了构造函数中
public function __construct($cache)
{
$this->cache = $cache;
}
和方法:
$this->cache->setItem('foo', 'bar');
echo $this->cache->getItem('foo');