Skip to content

Instantly share code, notes, and snippets.

@GuilhermeRossato
Created August 2, 2019 20:13
Show Gist options
  • Save GuilhermeRossato/b9a7e0a0b29fc36531c780824a5498d0 to your computer and use it in GitHub Desktop.
Save GuilhermeRossato/b9a7e0a0b29fc36531c780824a5498d0 to your computer and use it in GitHub Desktop.
Pure dependency-less memcache class implementation for development purposes that saves data to local storage.
<?php
// Ever needed to test an application that uses Memcache but didn't have it installed locally?
// This class saves its information to a local folder named "data" with the raw data passed to it.
// Each different key saved creates a new file on your system.
// Currently the only methods supported are Memcache::get and Memcache::set.
/**
* A class that mimicks the Memcache php dependency minimalistically by saving data to local storage.
*
* @usage:
* $memory = new Memcache();
* $memory->set("hello-world", "my stringifiable data");
*
* // On another random request or 300 days later at the artic:
*
* $memory = new Memcache();
* $message = $memory->get("hello-world");
* assert($message == "my stringifiable data");
*/
class Memcache {
private function key_to_filename($key) {
$str = strip_tags($key);
$str = preg_replace('/[\r\n\t ]+/', ' ', $str);
$str = preg_replace('/[\"\*\/\:\<\>\?\'\|]+/', ' ', $str);
$str = strtolower($str);
$str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
$str = htmlentities($str, ENT_QUOTES, "utf-8");
$str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
$str = str_replace(' ', '-', $str);
$str = rawurlencode($str);
$str = str_replace('%', '-', $str);
return $str;
}
/**
* Saves to persistent storage the value of a key
*
* @param string $key The key to identify the saved value so that it can be retrieved later.
* @param mixed $value The data as string to be saved to the file or the boolean 'false' to delete the key.
*/
public function set($key, $value) {
if (!is_dir(__DIR__."/data")) {
mkdir(__DIR__."/data");
}
$filename = $this->key_to_filename($key);
$filepath = __DIR__."/data/".$filename.".txt";
if ($value === false) {
unlink($filepath);
return;
}
file_put_contents($filepath, $value);
}
/**
* Retrieves from the persistent local storage the data previously saved as string.
*
* @param string $key The same key used to write data.
* @return mixed The false boolean value if it doesn't exist, a string with its content otherwise.
*/
public function get($key) {
if (!is_dir(__DIR__."/data")) {
return false;
}
$filename = $this->key_to_filename($key);
$filepath = __DIR__."/data/".$filename.".txt";
if (!file_exists($filepath)) {
return false;
}
return file_get_contents($filepath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment