Last active
December 1, 2015 15:50
-
-
Save Phocacius/a2f123843a5e993521e5 to your computer and use it in GitHub Desktop.
tiny php class to store tiny amounts of persistent data into a JSON file
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 | |
// helper class to store tiny amounts of data that should persist across sessions | |
class GlobalStorage { | |
private static $instance; | |
public static function getInstance() { | |
if(!self::$instance) { | |
self::$instance = new GlobalStorage(); | |
} | |
return self::$instance; | |
} | |
private $data; | |
private $storage; | |
public function __construct() { | |
$this->storage = __DIR__ . '/../data/global.json'; | |
$fileContent = is_file($this->storage) ? file_get_contents($this->storage) : false; | |
$this->data = $fileContent === false ? array() : json_decode($fileContent, true); | |
} | |
public function get($key, $default = null) { | |
return array_key_exists($key, $this->data) ? $this->data[$key] : $default; | |
} | |
public function set($key, $value, $instantSave = false) { | |
$this->data[$key] = $value; | |
if($instantSave) { | |
$this->persist(); | |
} | |
} | |
public function persist() { | |
file_put_contents($this->storage, json_encode($this->data, JSON_PRETTY_PRINT)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment