Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Easy to use memcache proxy class for php
Memcache Proxy Class for data
Furkan Mustafa, 2013.05
use it.
$dataUsedTooMuch = mem::cache('myhandle', 30, function() {
return db::query('SELECT CRAZY SLOW SQL SCRIPT');
class mem {
public static $conn = false;
public static $server = '';
public static $prefix = 'myKeyPrefix_';
public static function forceConnection() {
if (self::$conn) return true;
if (!self::$server) return false;
if (!class_exists('Memcache')) return false;
self::$conn = new Memcache();
$addressParts = explode(':', self::$server);
$port = (count($addressParts) > 1) ? array_pop($addressParts) : 11211;
$host = implode(':', $addressParts);
self::$conn->addServer($host, $port);
return true;
public static function get($name) {
if (!self::forceConnection()) return null;
return self::$conn->get(self::$prefix.$name);
public static function set($name, $var, $ttl = 300) {
if (!self::forceConnection()) return $var;
self::$conn->set(self::$prefix.$name, $var, 0, $ttl);
return $var;
public static function cache($name, $ttl, $block) {
$var = self::get($name);
if ($var) {
return $var;
$var = $block();
if (!$var) return $var;
self::set($name, $var, $ttl);
return $var;
public static function close() {
if (self::$conn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.