Last active
August 17, 2023 16:27
-
-
Save mrwadson/5327a2c2bd44ff85f03485b6b2b7b249 to your computer and use it in GitHub Desktop.
Cache in files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Usage [PHP >= 7.1] | |
* | |
require_once __DIR__ . '/Cache.php'; | |
$cache = new Cache(__DIR__ . '/cache.json'); | |
$cache->set('key1', ['key1' => 'value1']); | |
print_r($cache->get('key1')); | |
*/ | |
class Cache | |
{ | |
private $data; | |
private $file; | |
private $saved = false; | |
public function __construct(string $file) | |
{ | |
$this->file = $file; | |
if (file_exists($file)) { | |
$this->data = json_decode(file_get_contents($file), true); | |
} | |
} | |
public function get(string $key, callable $newDataCallback = null, bool $saveInFile = false) | |
{ | |
if (isset($this->data[$key])) { | |
return $this->data[$key]; | |
} | |
if ($newDataCallback && $newData = $newDataCallback()) { | |
$this->set($key, $newData, $saveInFile); | |
return $newData; | |
} | |
return null; | |
} | |
public function set(string $key, array $value, bool $saveInFile = false): void | |
{ | |
$this->data[$key] = $value; | |
if ($saveInFile) { | |
$this->save(); | |
} | |
} | |
public function save(): void | |
{ | |
if ($this->data) { | |
file_put_contents($this->file, json_encode($this->data)); | |
$this->saved = true; | |
} | |
} | |
public function __destruct() | |
{ | |
if (!$this->saved) { | |
$this->save(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment