<?php
/**
 * Memcache Lib
 * @package memcache.lib
 * @author Julius Beckmann
 * @link http://juliusbeckmann.de/code/
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @filesource
 */

/**
 * Returns a memcache handle or FALSE
 * The Instance will be kept inside this funtion, 
 * only a reference will be returned
 * @param string $ip
 * @param int $port Use 0 for unix sockets
 * @return &instance memcache
 */
function & memcache_instance($ip='127.0.0.1'$port=11211) {
    static 
$instance false;
    if(!
$instance)
        
$instance = @memcache_pconnect($ip$port); 
    return 
$instance;
}

/**
 * Sets a key/val in memcache
 * @param string $key
 * @param anything $var
 * @param int $ttl default=0
 * @param bool $compress default=false
 * @return bool true on success
 */
function cache_set($key$val$ttl=0$compress=false) {
    if(
defined('MEMCACHE_PREFIX'))
        
$key MEMCACHE_PREFIX.$key;
    if(
defined('MEMCACHE_SUFFIX'))
        
$key $key.MEMCACHE_SUFFIX;
    
// We NEED to use MEMCACHE_COMPRESSED (value=2), 
    // a simple TRUE (value=1) will NOT WORK!
    
return @memcache_set(memcache_instance(), $key$val,
                                                (
$compress) ? MEMCACHE_COMPRESSED 0$ttl);
}

/**
 * Fetches a key from memcache
 * @param string $key
 * @return data for $key or FALSE
 */
function cache_get($key) {
    if(
defined('MEMCACHE_PREFIX'))
        
$key MEMCACHE_PREFIX.$key;
    if(
defined('MEMCACHE_SUFFIX'))
        
$key $key.MEMCACHE_SUFFIX;
  return @
memcache_get(memcache_instance(), $key);
}

/**
 * Deletes a key from memcache
 * @param string $key
 * @param int $timeout default=0
 * @return bool true on success
 */
function cache_del($key$timeout=0) {
    if(
defined('MEMCACHE_PREFIX'))
        
$key MEMCACHE_PREFIX.$key;
    if(
defined('MEMCACHE_SUFFIX'))
        
$key $key.MEMCACHE_SUFFIX;
    return @
memcache_delete(memcache_instance(), $key$timeout);
}

/*------- Few examples: ---------*/

/* Memcache available ? */
//    if(!memcache_instance())
//        echo "Memcache not available!";
    
/* Save a key/value for 1 Minute */
//    if(cache_set('somename', 'somevalue', 60))
//        echo "somename has been saved!";

/* Get value for a key */
//    $val = cache_get('somename');
//    if($val)
//        echo "value of somename is $val";

/* Delete a key from memcache */
//    if(cache_del('somename'))
//        echo "somename has been deleted!";

?>