Key-value storage with map/filter with docs and tests
Jiri Knesl, submitted on 02/17/2011Very simple file-based storage working as k/v and map/filter. With tests in approximately 1 kilobyte! It allows you to use PHP callbacks. Usable on very very very simple websites as a storage.
Tags:
<?php /** * key value storage under 1kb including tests * save data to kvs.dat * * Usage: * kvs($key) - read key (allowed scalar values) * kvs($key, $value) - write value by key * kvs(function) - find values by callback (return true on match) * kvs(function, function) - find values by first callback (return true on match) and map by second (return value) * */ function kvs() { $map = null; $dataFile = __DIR__ . '/kvs.dat'; touch($dataFile); $data = unserialize(file_get_contents($dataFile)); $args = func_get_args(); if (array_key_exists(1, $args)) { if (is_scalar($args[0])) { $data[$args[0]] = $args[1]; file_put_contents($dataFile, serialize($data)); } else $map = $args[1]; } if (isset($args[0])) { if (is_scalar($args[0])) return $data[$args[0]]; else { $out = array_filter($data, $args[0]); if ($map) $out = array_map($args[1], $out); return $out; } } } /** tests */ kvs(); kvs("a", "b"); kvs("b", "c"); foreach (range(1,100) as $i) { kvs($i, $i); } assert('kvs("a") == "b"'); assert('kvs("b") == "c"'); assert('91+92+93+94+95+96+97+98+99+100 == array_sum(kvs(function($i){return $i>90;}))'); assert('-9-8-7-6-5-4-3-2-1 == array_sum(kvs(function($i){return $i>90;}, function($i){return $i - 100;}))');
blog comments powered by Disqus
CDP
Continuous Data Protection takes a snapshot of your site every six hours and allows you to restore as many or as few files as you wish; all done without talking to anyone but your keyboard. Add it in the order form.
Hosting Solutions
Web HostingReseller Hosting
Cloud Servers
Dedicated Servers
Domain Registration
Register a DomainDomain Hosting
Information Center
About WestHostContact Us
Media Center
Forum
Blog
Careers
Affiliates
Data Center
Terms & Policies
Site Map