JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
add persistent.php (key/value store)
[wfpl.git] / persistent.php
diff --git a/persistent.php b/persistent.php
new file mode 100644 (file)
index 0000000..cc12028
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+
+# a simple, persistent, key/value store optimized for many reads
+#
+# call persistent_{get,set,clear}
+
+# for internal use
+function persistent_init() {
+       if (isset($GLOBALS['wfpl_persistent'])) {
+               return;
+       }
+       $GLOBALS['wfpl_persistent'] = array();
+       $rows = db_get_rows('persistent', 'k,v');
+       foreach ($rows as &$row) {
+               $GLOBALS['wfpl_persistent'][$row[0]] = json_decode($row[1], true);
+       } unset($row);
+}
+
+function persistent_get($k) {
+       persistent_init();
+       if (isset($GLOBALS['wfpl_persistent'][$k])) {
+               return $GLOBALS['wfpl_persistent'][$k];
+       }
+       return null;
+}
+function persistent_set($k, $v) {
+       persistent_init();
+       if (isset($GLOBALS['wfpl_persistent'][$k])) {
+               if ($GLOBALS['wfpl_persistent'][$k] === $v) {
+                       return;
+               }
+               db_update('persistent', 'v', json_encode($v), 'where k=%"', $k);
+       } else {
+               db_insert('persistent', 'k,v', $k, json_encode($v));
+       }
+       $GLOBALS['wfpl_persistent'][$k] = $v;
+}
+function persistent_clear($k) {
+       persistent_init();
+       if (isset($GLOBALS['wfpl_persistent'][$k])) {
+               db_delete('persistent', 'where k=%"', $k);
+               unset($GLOBALS['wfpl_persistent'][$k]);
+       }
+}