I help a friend write a somewhat reasonable caching function for one of his scripts. It essentially uses 9 different SQL queries to retrieve leaderboard data (one of which is highly taxable)
I came up with the idea of creating a cache starting with this:
$cacheDir = "/cache";
$cachePath = "/var/www/html/test";
if (!file_exists($cachePath . $cacheDir))
{
mkdir($cachePath . $cacheDir, 0777, true);
}
$monsterCache = false;
$pvpCache = false;
$guildCache = false;
$cache = array_slice(scandir($cachePath . $cacheDir), 2);
$cacheSize = sizeof($cache);
Continuing work, I install some keys to determine whether we need to update or not, and then extract all the files and the size of the array containing all the files in the cache folder.
I follow this:
if ($cacheSize < 1) {
$monsterCache = true;
$pvpCache = true;
$guildCache = true;
} else {
for ($i = 0; $i < $cacheSize; $i++) {
if (preg_match('/^[0-9]+_monster_kills_leaderboard\.php/', $cache[$i], $cacheFile)) {
if (time() >= explode('_', $cacheFile[0])[0]) {
unlink($cachePath . $cacheDir . "/{$cache[$i]}");
$monsterCache = true;
}
} else {
$monsterCache = true;
}
if (preg_match('/^[0-9]+_pvp_leaderboard\.php/', $cache[$i], $cacheFile)) {
if (time() >= explode('_', $cacheFile[0])[0]) {
unlink($cachePath . $cacheDir . "/{$cache[$i]}");
$pvpCache = true;
}
} else {
$pvpCache = true;
}
if (preg_match('/^[0-9]+_guild_leader\.php/', $cache[$i], $cacheFile)) {
if (time() >= explode('_', $cacheFile[0])[0]) {
unlink($cachePath . $cacheDir . "/{$cache[$i]}");
$guildCache = true;
}
} else {
$guildCache = true;
}
}
}
What I do when creating and writing a cache file, I add a unix timestamp to represent how long it has been valid, separate it from the file name and compare the current time with the timestamp to determine if you want to delete the file and recreate it. (Timestamp_pvp_leaderboard.php)
:
if ($monsterCache) {
$monsterCache = false;
$cacheTTL = strtotime('+1 Hour', time());
<snip>
$data = array(
'Name, Kills' => $result[0]->__get("name") . ', ' . $result[0]->__get("kills"),
'Name, Kills' => $result[1]->__get("name") . ', ' . $result[1]->__get("kills"),
'Name, Kills' => $result[2]->__get("name") . ', ' . $result[2]->__get("kills")
);
foreach($data as $key => $val) {
file_put_contents($cachePath . $cacheDir . "/{$cacheTTL}_monster_kills_leaderboard.php", $key.', '.$val.PHP_EOL, FILE_APPEND | LOCK_EX);
}
}
, , , - (, , script ) . 3 .
, , .
- ? ?
?
, ! - , , , PHP.