Skip to content

Instantly share code, notes, and snippets.

@Phocacius
Last active December 1, 2015 15:50
Show Gist options
  • Save Phocacius/a2f123843a5e993521e5 to your computer and use it in GitHub Desktop.
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
<?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