JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
add persistent.php (key/value store)
authorJason Woofenden <jason@jasonwoof.com>
Tue, 7 Jul 2015 19:28:33 +0000 (15:28 -0400)
committerJason Woofenden <jason@jasonwoof.com>
Tue, 7 Jul 2015 19:28:33 +0000 (15:28 -0400)
examples/persistent.sql [new file with mode: 0644]
persistent.php [new file with mode: 0644]

diff --git a/examples/persistent.sql b/examples/persistent.sql
new file mode 100644 (file)
index 0000000..462b73c
--- /dev/null
@@ -0,0 +1,6 @@
+drop table if exists persistent;
+create table persistent (
+       k varchar(30) binary not null default "",
+       v varchar(255) binary not null default "",
+       primary key (k)
+) CHARSET=utf8;
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]);
+       }
+}