Skip to content

Instantly share code, notes, and snippets.

@audinue
Last active September 25, 2023 00:05
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/7301e02174f04b4b3b1cdd535a4bd041 to your computer and use it in GitHub Desktop.
Save audinue/7301e02174f04b4b3b1cdd535a4bd041 to your computer and use it in GitHub Desktop.
<?php
function kvstore ($file, $init = NULL) {
static $stores = [];
$store = @$stores[$file];
if (!$store) {
$prev = @file_get_contents($file);
if (!$prev) {
if ($init) {
$prev = json_encode((object) $init());
} else {
$prev = '{}';
}
}
$next = json_decode($prev);
$prev = json_decode($prev);
$stores[$file] = $store = $next;
register_shutdown_function(function () use ($file, $prev, $next) {
if ($prev != $next) {
file_put_contents($file, json_encode($next), LOCK_EX);
}
});
}
return $store;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment