mycacheclass mycache {
private $cache;
function __construct() {
$this->cache = new Memcache();
$this->cache->connect('localhost', 10987); // 依實際 IP/埠修改
}
function get_data($key) {
$data = $this->cache->get($key);
if($data != null) return $data;
else {
if($this->cache->getResultCode() == Memcached::RES_NOTFOUND) {
// 執行資料庫查詢並取得 $data_returned_from_database
$this->cache->set($key, $data_returned_from_database);
return $data_returned_from_database;
} else {
error_log('no data for key '.$key);
return false;
}
}
}
}
$cache = new mycache();
$cache->get_data('foo');
商品頁載入時,從快取取得商品簡介、運送資訊等,避免重複複雜查詢。後台更新商品時,同步更新對應快取 Key。