Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Super simple dirty flirty cache
<?php
/**
* Get a cached file, if not expired.
*
* @param string $file The cached filename.
* @param callable $prime A function used to prime the cache.
* @param int $expires After how many seconds the file expires.
*
* @return array|null Null if expired or unavailable.
*/
function getCachedFile($file, Closure $prime = null, $expires = 3600) {
$path = __DIR__ . '/cache/' . $file;
if (file_exists($path)) {
$data = json_decode(file_get_contents($path), true);
if ($data['expires'] < time()) {
deleteCachedFile($file);
} else {
return $data['contents'];
}
}
if (!is_null($prime)) {
$contents = $prime();
setCachedFile($file, $contents, $expires);
return $contents;
}
return null;
}
/**
* Create or overwrite a cached file.
*
* @param string $file A unique cache identifier used for the filename.
* @param string|array $contents The cache content.
* @param int $expires After how many seconds the file expires.
*/
function setCachedFile($file, $contents, $expires = 3600) {
$path = __DIR__ . '/cache/' . $file;
$data = [
'contents' => $contents,
'expires' => time() + $expires
];
file_put_contents($path, json_encode($data));
}
/**
* Delete a cached file.
*
* @param string $file The unique cache identiefier.
*/
function deleteCachedFile($file) {
$path = __DIR__ . '/cache/' . $file;
@unlink($path);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment