-
-
Save gotomypc/4051380 to your computer and use it in GitHub Desktop.
On-demand data retrieval between memcached and mysql in Codeigniter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* query_cache | |
* | |
* 查询缓存,返回数据集。如果缓存不存在或系统不支持缓存,则直接从model中提取。 | |
* | |
* | |
* @param string $key Key of the cache item | |
* @param string $model Model name from which we retrieve data | |
* @param string $method Method name of such model | |
* @param array $params Params given to such method | |
* @param int $ttl time to live of the cache item (in seconds) | |
* @return mixed Cached data | |
*/ | |
function query_cache($key, $model, $method, $params = array(), $ttl = 1296000) | |
{ | |
$CI = & get_instance(); | |
// Required model not loaded? | |
// Load models on demand | |
if( ! in_array($model, $CI->load->_ci_models, TRUE)) | |
{ | |
$CI->load->model($model); | |
} | |
// Ref this model | |
$handler = & $CI->$model; | |
// Cache is disabled when we are in DEV or other unkonwn situations | |
if( ! $CI->cache->memcached->is_supported()) | |
{ | |
return call_user_func_array(array($handler, $method), $params); | |
} | |
// Valid cache item? If so, we've done! | |
if( ! $data = $CI->cache->memcached->get($key)) | |
{ | |
// Fetch data from model | |
$data = call_user_func_array(array($handler, $method), $params); | |
// WARINING: EMPTY results (such as 0, FALSE) may be ignored! | |
if( ! empty($data)) | |
{ | |
// Make the results cacheable! | |
$CI->cache->memcached->save($key, $data, $ttl); | |
} | |
} | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment