Class MemcacheModel { Private $ mc = null; /** * Constructor is used to add a server and create a memcahced object. */ Function _ construct (){ $ Params = func_get_args (); $ Mc = new Memcache; // If multiple memcache servers exist 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 the memcached object * @ Return object memcached object */ Function getMem (){ Return $ this-> mc; } /** * Check whether mem connection is successful. * @ Return true if the bool connection is successful; otherwise, false is returned. */ Function mem_connect_error (){ $ Stats = $ this-> mc-> getStats (); If (empty ($ stats )){ Return false; } Else { Return true; } } Private function addKey ($ tabName, $ key ){ $ Keys = $ this-> mc-> get ($ tabName ); If (empty ($ keys )){ $ Keys = array (); } // If the key does not exist, add If (! In_array ($ key, $ keys )){ $ Keys [] = $ key; // add the new key to the keys of the table $ This-> mc-> set ($ tabName, $ keys, MEMCACHE_COMPRESSED, 0 ); Return true; // return true if no data exists. } Else { Return false; // If yes, false is returned. } } /** * Add data to memcache * @ Param string $ tabName: name of the table whose data table needs to be cached * @ Param string $ SQL uses SQL as the memcache key * @ Param mixed $ data the data 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 stored in memcahce * @ Param string $ SQL uses the SQL key * @ Return mixed return the cached data */ Function getCache ($ SQL ){ $ Key = md5 ($ SQL ); Return $ this-> mc-> get ($ key ); } /** * Delete all caches related to the same table * @ Param string $ tabName table name */ Function delCache ($ tabName ){ $ Keys = $ this-> mc-> get ($ tabName ); // Delete all the caches of the same table If (! Empty ($ keys )){ Foreach ($ keys as $ key ){ $ This-> mc-> delete ($ key, 0); // 0 indicates immediate deletion } } // Delete the keys of all SQL statements in the table $ This-> mc-> delete ($ tabName, 0 ); } /** * Delete the cache of a separate statement * @ Param string $ SQL statement executed */ Function delone ($ SQL ){ $ Key = md5 ($ SQL ); $ This-> mc-> delete ($ key, 0); // 0 indicates immediate deletion } }
|