Skip to content

Instantly share code, notes, and snippets.

@mesbahulalam
Last active July 13, 2021 00:51
Show Gist options
  • Save mesbahulalam/a7aec531812910c3734c984942d09816 to your computer and use it in GitHub Desktop.
Save mesbahulalam/a7aec531812910c3734c984942d09816 to your computer and use it in GitHub Desktop.
<?php
class jsondb
{
public $result;
private $file;
private $data;
function __construct($file = "test43"){
if(!file_exists($file)) fclose(fopen($file, "w+"));
if(!$this->file) $this->file = $file;
if(!isset($this->data)) $this->data = ($try = json_decode(file_get_contents($this->file), true)) != false ? $try : array();
}
function read($key = null){
return $key !== null ? ($this->data[$key] ? $this->data[$key] : "Record not found.") : $this->data;
}
function write($value, $key = null, $replace = false){
if($key && array_key_exists($key, $this->data)){
if($replace == "delete"){
unset($this->data[$key]);
return $this->commit();
}elseif($replace === true ){
$this->data[$key] = $value;
return $this->commit();
}else{
return "Key already exists,";
}
}
$key !== null ? $this->data[$key] = $value : $this->data[] = $value;
return $this->commit();
}
private function commit($data = false){
return file_put_contents($this->file, json_encode(($data ? $data : $this->data)));
}
}
// cleanup if needed
// unlink("test43");
/*
Supports the basic 4 operations.
Create ->write(value, key)
Read ->read(key) No key will provide the entire database.
Update ->write(value, key, true) Overwrite check is off.
Delete ->write(value, key, "delete")
*/
$app = new jsondb();
// tests
// Write some demo data
// $app->write("Some value");
// $app->write("Some value 1", "Some Key 1");
// $app->write("Some other value");
// $app->write("Some value 2", "Some Key 2");
// Data is preserved if an existing key is entered.
// echo $app->read("Some Key 2");
// $app->write("Some new value 2", "Some Key 2");
// echo $app->read("Some Key 2");
// Data is updated
// $app->write("Some new value 2", "Some Key 2", true);
// echo $app->read("Some Key 2");
// Data is deleted by key
// $app->write(1, 1, "delete");
// echo $app->read("Some Key 2");
?>
<textarea><?php print_r(json_decode(file_get_contents("test43"), true)); ?></textarea>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment