1

在 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
  }
}
4

1 回答 1

2

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
  }
}
于 2016-02-02T10:30:39.360 回答