Skip to content

Instantly share code, notes, and snippets.

@jxxe
Last active January 6, 2024 12:15
Show Gist options
  • Save jxxe/88a2ca6e21230416229c2870809ccc32 to your computer and use it in GitHub Desktop.
Save jxxe/88a2ca6e21230416229c2870809ccc32 to your computer and use it in GitHub Desktop.
A quick and dirty PHP class to cache JSON data
<?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);
}
}
@jxxe
Copy link
Author

jxxe commented Jul 1, 2021

Sample usage:

require_once "Cache.php";
$cache = new Cache("cache/api/items", HALF_DAY); // create a directory at cache/api/items that will last half a day

$items;
if($cache->checkCache()) {
    $items = $cache->getCache();
} else {
    $items = "[1,2,3,4,5]"; // however you get the JSON data you want to cache
    $cache->addData($items);
}

echo $items;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment