缓存文件的超时(以 php 为单位)


Timeout for a cache file in php

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

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