Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php declare(strict_types=1);
- define('CACHE_FILE','/home/seb/.cache/test_php_{file}.txt');
- print 'get(yep) -> '.get('yep').PHP_EOL;
- print 'cache file for yep : '.cache_file_path('yep');
- function get(string $x): ?string {
- return cached($x) ?? fetch($x); // @todo fetch is not supposed to cache, no implicite.
- }
- function cached(string $x): ?string {
- $content = fread(cache_file_stream($x),filesize(cache_file_path($x)));
- return $content === false ? null : $content;
- }
- function fetch(string $x): ?string {
- $content = (string)time(); // fake content
- throw new \LogicException('re implement this');
- return cache($x, $content);
- }
- function cache(string $x, string $content): string {
- if(false === fwrite(cache_file_stream($x), $content)) {
- throw new FailToWriteToFile(cache_file_path($x));
- };
- return $content;
- }
- /** @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,['{file}' => crc32($x)]);
- }
Add Comment
Please, Sign In to add comment