Zend_Cache-检索过期数据



我使用Zend_Cache缓存从web服务生成的数据。但是,如果web服务没有响应,我希望显示过时的信息,而不是留下空白。

根据文件,答案是将第二个参数传递给Zend_Cache_Core::load():

@param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested

然而,对于我所做的每一次测试,都会为过期的缓存内容返回bool(false)

有没有办法强制Zend_Cache返回给定缓存密钥的缓存数据,即使它已经过期?

$cache_key = md5($url);
if ($out = $cache->load($cache_key)) {
  return $out;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
if ($output) {
  // Process...
  $cn_cache->save($out, $cache_key);
} else {
  // The query has timed out/web service not responded
  // We need to load the outdated cached content... but the following DOES NOT work
  return $cache->load($cache_key, true);
  // var_dump($cache->load($cache_key, true)); # false
}

我想不出一种可靠的方法来做到这一点,除了让永远不会过期的对象的第二个缓存版本。如果在对象上设置了X秒的缓存过期时间,那么根本无法保证该对象在X秒后仍然存在。

以下是建议的解决方法示例。。。

...
$cache_key_forever = sha1($url)
if ($output) {
  // Process...
  $cn_cache->save($out, $cache_key);
  $cn_cache->save($out, $cache_key_forever, array(), null); // The "null" parameter is the important one here: save cache indefinitely
} else {
  // The query has timed out/web service not responded
  // Load the infinitely persisted cache object
  return $cache->load($cache_key_forever);
  // var_dump($cache->load($cache_key, true)); # false
}

最新更新