yivi yivi - 6 months ago 39
PHP Question

ZF2 Redis Adapter: getting TTL or setting a new expiration for a key?

Redis is able to give back TTL for a key, or setting a new expiration time; but I can't see how to achieve the same using ZF2 Redis Cache Storage Adapter.

I know I can set a default TTL for each adapater instance, but I'd need to be able to know how many seconds a value has left, or to be able to 'touch' a value, extending its life, or to even set a new expiration explicitely.

Is it possible that there is now way to achieve any of this using Zend's adapter? Any way to circumvent this and do it directly?

Answer

You can use following convention to set temporary expire value. I don't know how you can get expire time

/**
 * @var \Zend\Cache\Storage\Adapter\Redis $redisCache
 */
$redisCache = $this->getServiceLocator()->get('core.cache.redis');
$tempTtl = $redisCache->getOptions()->getTtl();
$redisCache->getOptions()->setTtl(5);
var_dump($redisCache->setItem('test', '123456'));
$redisCache->getOptions()->setTtl($tempTtl);

You should use TTL command to know how many seconds has left for a key on your Redis Command line. But Zend Cache does not handle this command. If you want to use this command, you can extend zend default adapter (\Zend\Cache\Storage\Adapter\Redis) and add your functionality to there. And change your config according to your custom Adapter.