Last active
September 25, 2023 00:05
-
-
Save audinue/7301e02174f04b4b3b1cdd535a4bd041 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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