To administer your WestHost account, please enter your
Domain Name or Server Manager Username.

WestHost
  • getCenter

    By subrahmanyam, submitted on 03/15/2011
  • Image Compress & Resize

    By Arivazhagan, submitted on 03/14/2011
  • AmPM

    By Ali A, submitted on 03/13/2011
  • mysqlToHuman

    By Ali a, submitted on 03/13/2011
  • time_ago

    By Bui Hoang Hai, submitted on 03/11/2011

VIEW MORE ENTRIES


Key-value storage with map/filter with docs and tests

Jiri Knesl, submitted on 02/17/2011

Very 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.

Average rating 1.9333 / 90 Votes

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;}))');
 
Share |

blog comments powered by Disqus
 
 
Follow WestHost: Twitter Facebook Copyright © 1998–2010, WestHost. All rights reserved.  |  WestHost / Believe in Better Hosting.
Chat Live Now