比较省资源的PHP简单的MEMCACHE助手类代码分享

<?php if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/**
 * 这个助手类主要特色,Memcache链接复用,一个http请求只使用一个Memcache链接
 * 使用Key前缀,使多个项目共享Memcache
 */
class Mcache
{
    static $conn = null;
 
    static function connect()
    {
        //若是已经有链接,则不在建立新的链接
        if (is_object(self::$conn)) {
            return self::$conn;
        }
 
        $server = array(
            array(
                'host' => '127.0.0.1',
                'port' => '11211'
            )
        );
 
        self::$conn = new Memcache;
        for ($i = 0; $i < count($server); $i++) {
            self::$conn->addServer($server[$i]['host'], $server[$i]['port'], false);
        }
 
        return self::$conn;
    }
 
    /**
     * 当要使用助手类没有封装的Memcache方法时,用这个方法获取key
     * @param $key
     * @return string
     */
    static function key($key)
    {
        return md5('zzj.net_' . $key);
    }
 
    static function read($key)
    {
        $key = md5('zzj.net_' . $key);
 
        $ret = null;
        if ($conn = self::connect($key)) {
            $ret = $conn->get($key);
        }
        return $ret;
    }
 
    static function write($key, $val, $expire = 0, $flag = 0)
    {
        $key = md5('zzj.net_' . $key);
 
        $ret = null;
        if ($conn = self::connect($key)) {
            $ret = $conn->set($key, $val, $flag, $expire);
        }
        return $ret;
    }
 
    static function delete($key, $expire = 0)
    {
        $key = md5('zzj.net_' . $key);
 
        $ret = null;
        if ($conn = self::connect($key)) {
            $ret = $conn->delete($key, $expire);
        }
        return $ret;
    }
}
相关文章
相关标签/搜索