-
- class MemcacheModel {
- private $mc = null;
- /**
- * Constructor method, used to add servers and create memcahced objects
- */
- function __construct(){
- $params = func_get_args();
- $mc = new Memcache;
- //If there are multiple memcache servers
- if( count($params) > 1){
- foreach ($params as $v){
- call_user_func_array(array($mc, 'addServer'), $v);
- }
- //If there is only one memcache server
- } else {
- call_user_func_array(array($mc, 'addServer'), $params[0]);
- }
- $this->mc=$mc;
- }
- / **
- * Get memcached object
- * @return object memcached object
- */
- function getMem(){
- return $this->mc;
- }
- /**
- * Check whether mem is connected successfully
- * @return bool Returns true if the connection is successful, otherwise returns false
- */
- function mem_connect_error(){
- $stats=$this->mc- >getStats();
- if(emptyempty($stats)){
- return false;
- }else{
- return true;
- }
- }
-
- private function addKey($tabName, $key){
- $keys=$ this->mc->get($tabName);
- if(emptyempty($keys)){
- $keys=array();
- }
- //If the key does not exist, add one
- if(!in_array ($key, $keys)) {
- $keys[]=$key; //Add new keys to the keys of this table
- $this->mc->set($tabName, $keys, MEMCACHE_COMPRESSED , 0);
- return true; //return true if it does not exist
- }else{
- return false; //return false if it exists
- }
- }
- /**
- * Add data to memcache
- * @param string $tabName The name of the data table that needs to be cached
- * @param string $sql Use sql as the key of memcache
- * @param mixed $data The data that needs to be cached
- */
- function addCache($tabName, $sql, $data){
- $key=md5($sql);
- //If it does not exist
- if($this->addKey($tabName, $key)){
- $this->mc->set( $key, $data, MEMCACHE_COMPRESSED, 0);
- }
- }
- /**
- * Get the data saved in memcahce
- * @param string $sql Use SQL key
- * @return mixed Return the data in the cache
- */
- function getCache($sql){
- $key=md5($sql);
- return $this->mc ->get($key);
- }
-
- /**
- * Delete all caches related to the same table
- * @param string $tabName The table name of the data table
- */
- function delCache($tabName){
- $keys=$this->mc->get($tabName);
- / /Delete all caches of the same table
- if(!emptyempty($keys)){
- foreach($keys as $key){
- $this->mc->delete($key, 0); //0 Indicates immediate deletion
- }
- }
- //Delete all sql keys of the table
- $this->mc->delete($tabName, 0);
- }
- /**
- * Delete the cache of a single statement
- * @param string $sql SQL statement executed
- */
- function delone( $sql){
- $key=md5($sql);
- $this->mc->delete($key, 0); //0 means delete immediately
- }
- }
- ?>
Copy Code
|