Skip to content

Instantly share code, notes, and snippets.

@SebSept
Last active March 15, 2020 10:36
Show Gist options
  • Save SebSept/78d508bace4c1d611e71ed6e0f09506a to your computer and use it in GitHub Desktop.
Save SebSept/78d508bace4c1d611e71ed6e0f09506a to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
// this may be defined in the enviroment, not in the code.
// or can we find a system path for auto setup persistent cache ?
define('CACHE_FILE_TEMPLATE','/home/seb/.cache/test_php_{file}.txt');
// usage : get some data : get('the key') // return some string content
print 'get("the stuff to fetch") -> "'.get('some stuffx.').'"'.PHP_EOL;
// you can also use the 'tool' functions
//print 'cache file for yep : '.cache_file_path('yep');
// --- the functions ---
// main function
function get(string $key): ?string {
return cached($key) ?? cache($key, fetch($key) );
}
function cached(string $key): ?string {
$content = @fread(cache_file_stream($key),filesize(cache_file_path($key)));
return $content === false ? null : $content;
}
function fetch(string $x): string {
return "$x content, fetched at ".(new DateTime())->format(DateTime::RFC822);
}
function cache(string $key, string $content): string {
if(false === fwrite(cache_file_stream($key), $content)) {
throw new FailToWriteToFile(cache_file_path($key));
};
return $content;
}
// --- sub functions ---
/** @return resource */
function cache_file_stream(string $x)/*: resource*/ {
if(false === ($resource = fopen(cache_file_path($x), 'c+'))) {
throw new FailToOpenFile(cache_file_path($x));
}
return $resource;
}
function cache_file_path(string $x): string {
return strtr(CACHE_FILE_TEMPLATE,['{file}' => crc32($x)]);
}
class FailToOpenFile extends \RuntimeException {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment