Last active
September 25, 2024 20:51
-
-
Save jxxe/88a2ca6e21230416229c2870809ccc32 to your computer and use it in GitHub Desktop.
A quick and dirty PHP class to cache JSON data
This file contains hidden or 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 | |
const MONTH = "Y-m"; // 2000-01 | |
const DAY = "Y-m-d"; // 2000-01-01 | |
const HALF_DAY = "Y-m-d-A"; // 2000-01-01-AM | |
const HOUR = "Y-m-d-H"; // 2000-01-01-24 | |
const MINUTE = "Y-m-d-H-i"; // 2000-01-01-24-60 | |
class Cache { | |
private $directory; | |
private $lifespan; | |
public function __construct($directory, $lifespan) { | |
$this->directory = $directory; | |
$this->lifespan = $lifespan; | |
if(!is_dir("$directory/.")) { | |
mkdir($directory, 0777, true); | |
} | |
} | |
/** | |
* Add data to the cache | |
* | |
* @param string $json The JSON data to store | |
* @param boolean $clearCache Whether or not to remove other files inside the cache when adding data | |
* @return void | |
*/ | |
public function addData($json, $clearCache = true) { | |
if($clearCache) $this->clearCache(); | |
file_put_contents("$this->directory/{$this->generateDate()}.json", $json); | |
} | |
/** | |
* Check cache data | |
* | |
* @return boolean Returns true if the data in the cache is up to date, false if it needs to be updated | |
*/ | |
public function checkCache() { | |
return file_exists("$this->directory/{$this->generateDate()}.json"); | |
} | |
/** | |
* Get cache data | |
* | |
* @return string A string of JSON data from the cache | |
*/ | |
public function getCache() { | |
return file_get_contents("$this->directory/{$this->generateDate()}.json"); | |
} | |
/** | |
* Clear cache | |
* | |
* @return void | |
*/ | |
public function clearCache() { | |
array_map("unlink", glob("$this->directory/*.json")); | |
} | |
/** | |
* Generate cache date | |
* | |
* @return string An up-to-date file name to store and check cache files against | |
*/ | |
private function generateDate() { | |
return (new DateTime)->format($this->lifespan); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage: