Last active
December 17, 2015 19:29
-
-
Save furkanmustafa/5660935 to your computer and use it in GitHub Desktop.
Easy to use memcache proxy class for php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Memcache Proxy Class for data | |
Furkan Mustafa, 2013.05 | |
use it. | |
usage: | |
$dataUsedTooMuch = mem::cache('myhandle', 30, function() { | |
return db::query('SELECT CRAZY SLOW SQL SCRIPT'); | |
}); | |
*/ | |
class mem { | |
public static $conn = false; | |
public static $server = '127.0.0.1'; | |
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) | |
self::$conn->close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment