Skip to content

Instantly share code, notes, and snippets.

@LiamKarlMitchell
Last active April 2, 2019 22:20
Show Gist options
  • Save LiamKarlMitchell/cc1c7a167f399457cb5198d46ea152f2 to your computer and use it in GitHub Desktop.
Save LiamKarlMitchell/cc1c7a167f399457cb5198d46ea152f2 to your computer and use it in GitHub Desktop.
Load data from and save it to a JSON file on php shutdown exit close.
<?php
namespace LiamKarlMitchell\File;
class JSONFile
{
public $filename;
private $data = array();
public function __construct($filename, $defaults = array())
{
$this->filename = $filename;
$this->data = $defaults;
$this->load();
register_shutdown_function(array($this, '__shutdown'));
}
public function __shutdown() {
$this->save();
}
public function load()
{
if (file_exists($this->filename)) {
$input = file_get_contents($this->filename);
$this->data = json_decode($input, true);
}
}
public function save()
{
file_put_contents($this->filename, json_encode($this->data));
}
public function __get($key)
{
if (isset($this->data[$key])) {
return $this->data[$key];
} else {
return undefined;
}
}
public function __set($key, $value)
{
$this->data[$key] = $value;
}
public function __isset($key)
{
return isset($this->data[$key]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment