<?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; } }