【问题标题】:Timeout for a cache file in phpphp中缓存文件的超时
【发布时间】:2016-05-11 02:17:14
【问题描述】:

在 php 中,我创建了一个缓存文件以存储复杂的结果变量。一个变量,一个缓存文件。干得好。

问题在于缓存的期限。目前我将超时和变量放入文件中,但它没有优化,因为我必须打开文件来检查超时。

我想(如果可能的话)检查文件属性的超时时间(例如使用函数 filemtime() 上次修改的日期)。我们可以将自定义属性添加到文件中吗?

另一种方法是在文件名中添加超时,不是我最喜欢的解决方案。

[编辑]

final class Cache_Var extends Cache {

  public static function put($key, $value, $timeout=0) {
    // different timeout by variable (if 0, infinite timeout)
  }

  public static function get($key) {
    // no timeout to get a var cache
    // return null if file not found, or if timeout expire
    // return var otherwise
  }
}

【问题讨论】:

  • 无法添加自定义属性,但mtime 有什么问题?
  • 如果每个 var 缓存具有相同的超时时间,我可以使用 mtime。如果没有,我必须另寻出路。

标签: php file caching filetime cache-expiration


【解决方案1】:

filectime()真的可以帮到你

$validity = 60 * 60; // 3600s = 1 hour
if(filectime($filename) > time() - $validity) {
  // cache is valid
} else {
  // cache is invalid: recreate it
}

周围有一些缓存 fdrameworks 正是使用这种机制。

编辑: 如果每个缓存项需要不同的超时时间,而不是使用touch()来设置缓存文件的修改时间。您甚至可以将修改时间设置为未来值,并直接将filectime 与当前时间进行比较。

final class Cache_Var extends Cache {

  public static function put($key, $value, $timeout=0) {
    // different timeout by variable (if 0, infinite timeout)
    // ...
    touch($filename, time() + $timeout);

    // For static files with unlimited lifetime I would simply store
    // them in a separate folder
  }
}

【讨论】:

  • 我编辑我的请求。 get函数无法识别超时,我必须搜索它。我仍然将您的解决方案用于具有全局超时的缓存页面,但不适用于我的缓存变量。
  • 好吧,我不知道这个功能。谢谢@maxhb,这正是缺少的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
相关资源
最近更新 更多