最干净的方法是
APC
(可选的php缓存)如果安装了。这有一个内置的“生存时间”功能:
if (apc_exists('twitter_result')) {
$twitter_result = apc_fetch('twitter_result');
} else {
$twitter_result = file_get_contents('http://twitter.com/...'); // or whatever your API call is
apc_store('twitter_result', $twitter_result, 10 * 60); // store for 10 mins
}
我可以选择在数据上超时10分钟。这取决于订阅源更新的频率…
编辑
如果没有安装APC,可以使用一个非常简单的文件:
if (file_exists('twitter_result.data')) {
$data = unserialize(file_get_contents('twitter_result.data'));
if ($data['timestamp'] > time() - 10 * 60) {
$twitter_result = $data['twitter_result'];
}
}
if (!$twitter_result) { // cache doesn't exist or is older than 10 mins
$twitter_result = file_get_contents('http://twitter.com/...'); // or whatever your API call is
$data = array ('twitter_result' => $twitter_result, 'timestamp' => time());
file_put_contents('twitter_result.data', serialize($data));
}