Skip to content

Instantly share code, notes, and snippets.

@audinue
Created September 24, 2023 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/aa9a66aaea29bbb6490a26ca85e0d6c9 to your computer and use it in GitHub Desktop.
Save audinue/aa9a66aaea29bbb6490a26ca85e0d6c9 to your computer and use it in GitHub Desktop.

database

Simple flat file NoSQL database.

initialize a database

$db = database('blog.json');

get a collection

$posts = $db->get('posts');

insert or update a document

$posts->put([
  'id' => '1',
  'title' => 'Hello world!'
]);

delete a document

$posts->delete('1');

get a document

var_dump($posts->get('1'));

iterate a collection

foreach ($posts as $id => $post) {
  var_dump($id);
  var_dump($post);
}
<?php
function database($file) {
static $databases = [];
$database = @$databases[$file];
if (!$database) {
$database = new class($file) {
private $file;
private $previous;
private $next;
function __construct($file) {
$this->file = $file;
$json = @file_get_contents($file);
if (!$json) {
$json = '{}';
}
$this->previous = json_decode($json);
$this->next = json_decode($json); // deep copy
}
function __destruct() {
if ($this->previous != $this->next) {
file_put_contents($this->file, json_encode($this->next), LOCK_EX);
}
}
function get($name) {
$documents = @$this->next->$name;
if (!$documents) {
$documents = new stdClass();
$this->next->$name = $documents;
}
return new class($documents) implements IteratorAggregate
{
private $documents;
function __construct($documents) {
$this->documents = $documents;
}
function get($id) {
return $this->documents->$id;
}
function put($next) {
$previous = @$this->documents->{$next['id']};
if ($previous) {
foreach ($next as $key => $value) {
$previous->$key = $value;
}
} else {
$this->documents->{$next['id']} = (object) $next;
}
}
function delete($id) {
unset($this->documents->$id);
}
function getIterator(): Traversable {
return new ArrayIterator($this->documents);
}
};
}
};
$databases[$file] = $database;
}
return $database;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment