phpcms使用的緩存方式總結

 最近在研究PHPCMS系統,今天與大家分享的是PHPCMS系統的緩存方式總結,如果大家有覺得不對的地方請指出來

phpcms使用的緩存方式總結
a.模板編譯緩存

參考文件include/global.func.php及include/template.func.php
模板編譯緩存的原理其實很簡單,如果模板是第一次編譯,則直接編譯它,如果不是第一次編譯,則比較模板文件($tplfile)及模板緩存文件 ($compiledtplfile)的修改時間,如果模板文件的修改時間大於編譯過的模板緩存文件,則編譯模板,否則不編譯模板,提高了程序的執行效率。
function template($module = 'phpcms', $template = 'index')
{
    global $CONFIG;
    $compiledtplfile = $CONFIG['templatescachedir'].$module.'_'.$template.'.tpl.php';
    if($CONFIG['templaterefresh'])
    {
        $tplfile = PHPCMS_ROOT.'/templates/'.$CONFIG['defaulttemplate'].'/'.$module.'/'.$template.'.html';
        if(!file_exists($compiledtplfile) || @filemtime($tplfile) > @filemtime($compiledtplfile))
        {
            require_once PHPCMS_ROOT.'/include/template.func.php';
            template_refresh($tplfile, $compiledtplfile);
        }
    }
    return $compiledtplfile;
}

b.在動態頁面裏面產生靜態的緩存文件
與c的緩存原理類似,只是此處生成的文件名相對固定
以問吧模塊爲例進行說明
用http://www.chf.com/opensource/phpcms2007_sp6_gbk/phpcms/wenba/進行訪問
此目錄下有個index.php文件,判斷當前目錄下是否存在名爲index_cache.html的文件,如果有沒有過失效期,則直接包含此文件,否則動態地讀取完數據後保存爲index_cache.html文件,以備下次使用。
文件index.php中的內容:
<?php
require_once './include/common.inc.php';
$lastedittime = @filemtime('index_cache.html');
$lastedittime = $PHP_TIME-$lastedittime;
$autoupdatetime = intval($MOD['autoupdate']); //$MOD['autoupdate']來自緩存文件data/cache/wenba_setting.php中的內容
if(file_exists('index_cache.html') && $lastedittime<$autoupdatetime)
{   
    echo "include cache file";
    include 'index_cache.html';
}
else
{
    echo "read dynamic page";
...
?>
怎麼判斷文件是否失效呢,文件data/cache/wenba_setting.php中有如下的設置,其中字段autoupdate的值就是文件失效的時間,單位是秒,在後臺可以進行設置
文件wenba_setting.php是從哪兒來的呢,進行安裝時自動把各種模塊的數據保存到數據庫中了,安裝時就生成緩存數據了,在include/common.inc.php中函數cache_all也可以生成緩存,後臺進行設置時cache會自動更新的
<?php
 return array (
  'higth_score' => '100',
  'anybody_score' => '2',
  'answer_give_credit' => '5',
  'vote_give_credit' => '1',
  'highscore' => '2',
  'vote_give_actor' => '公司白領

魔法師

科舉奪魁

武將

江湖奇俠',
  'autoupdate' => '10',
  'name' => '問吧',
  'moduledir' => 'wenba',
  'moduledomain' => '',
  'linkurl' => '/opensource/phpcms2007_sp6_gbk/phpcms/wenba/',
);
?>

include/global.func.php
更新模塊設置函數
function module_setting($module, $setting)
{
    global $db,$MODULE,$LANG;
    if(!is_array($setting) || !array_key_exists($module,$MODULE)) return FALSE;
    if(isset($setting['moduledomain']))
    {
        $moduledomain = $setting['moduledomain'];
        $db->query("UPDATE ".TABLE_MODULE." SET moduledomain='$moduledomain' WHERE module='$module'");
        unset($setting['moduledomain']);
    }
    $setting = addslashes(serialize(new_stripslashes($setting)));
    //將某個模塊的多個設置的值經數組序列化以後保存在一個字段setting中
    $db->query("UPDATE ".TABLE_MODULE." SET setting='$setting' WHERE module='$module'");
    cache_module($module);
    cache_common();
    return TRUE;
}

c.在動態頁面裏面產生靜態的緩存文件
與b的緩存原理類似,只是此處生成的文件名是根據計算$PHP_SELF與$PHP_QUERYSTRING的md5值生成的文件名,相對於所有php動態頁面來說都是一樣的,這個思想比較精典,值得借籤
以問吧模塊爲例進行說明
文件調用順序爲:index.php -> js.php -> ad.php -> global.func.php
用http://www.chf.com/opensource/phpcms2007_sp6_gbk/phpcms/wenba/進行訪問
此目錄下有個index.php文件,判斷當前目錄下是否存在名爲index_cache.html的文件,如果有,則直接包含此文件,如果不存在此文件,則動態地讀取完數據後保存在index_cache.html文件,以備下次使用

用上述的url訪問時,頁面裏面包含有如下的一行js代碼
<script language="javascript" src="/opensource/phpcms2007_sp6_gbk/phpcms/data/js.php?id=1"></script>
此js代碼其實就是動態調用php頁面的內容
http://www.chf.com/opensource/phpcms2007_sp6_gbk/phpcms/data/js.php?id=1

js.php文件的內容:
<?php
chdir('../ads/');
require './ad.php';
?>

ad.php的內容:
<?php
define('SHOWJS', 1);
require './include/common.inc.php';
require MOD_ROOT.'/include/global.func.php';

$placeid = intval($id);

$query ="SELECT * FROM ".TABLE_ADS." AS a LEFT JOIN ".TABLE_ADS_PLACE." AS p ON (a.placeid=p.placeid) WHERE a.placeid=".$placeid." AND a.fromdate<=UNIX_TIMESTAMP() AND a.todate>=UNIX_TIMESTAMP() AND p.passed=1 AND a.passed=1 AND a.checked=1 ORDER BY a.addtime";
$ads = $db->get_one($query, "CAHCE", 10240);
if(!$ads) exit('document.write("")');

$db->query("UPDATE ".TABLE_ADS." SET views=views+1 WHERE adsid=".$ads['adsid']);

$content = ads_content($ads);
$templateid = $ads['templateid'] ? $ads['templateid'] : 'ads';
include template('ads', $templateid);
phpcache();
?>

ad.php裏面調用了phpcache函數,參考文件include/global.func.php
function phpcache($is_js = 0)
{
    global $CONFIG,$cachefiledir,$cachefile;
    if(!$is_js && $CONFIG['phpcache'] != '2') return FALSE;
    $contents = ob_get_clean(); //讀取緩衝區裏面的內容
    if($is_js) $contents = strip_js($contents);
    if($CONFIG['phpcache'] == '2' && $cachefiledir && $cachefile)
    {
        dir_create($cachefiledir);
        file_put_contents($cachefile, $contents); //在這兒生成一個.html格式的文件,當下次以同樣的url訪問時,會直接讀取緩存了,參見include/common.inc.php中的代碼,這兒的代碼是非常非常精典的,大家好好借鑑、好好模仿吧
        @chmod($cachefile, 0777);
    }
    /*
    向瀏覽器發送http header,跟瀏覽器說,此頁面不緩存,還告訴瀏覽器頁面的最後修改時間
    第一次訪問js.php?id=1時向瀏覽器發送http header,第二次或以後再訪問此url時,由於上次已經生成了緩存,所以在include/common.inc.php中直接調用緩存文件了,直到緩存失效後再次執行此處的動態代碼。此處發送的header控制緩存是相對於瀏覽器來說的;而通過file_put_contents生成的緩存是相對於電腦硬盤來說的,是不一樣的。
    */
    header('Expires: Mon, 26 Jul 2000 05:00:00 GMT');
    header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: no-cache');
    echo $contents;
}

上面的phpcache函數中的全局變量$cachefiledir,$cachefile是從哪裏來的呢,從這兒來的
文件include/common.inc.php中的內容
if(!defined('IN_ADMIN'))
{
    if($CONFIG['dbiscache']) $db_file .= '_cache';
    if($CONFIG['phpcache'] == '2')
    {
        $cachefileid = md5($PHP_SELF.'?'.$PHP_QUERYSTRING);
        $cachefiledir = PHPCMS_ROOT.'/data/phpcache/'.substr($cachefileid, 0, 2).'/';
        $cachefile = $cachefiledir.$cachefileid.'.html';
        //echo "cachefile:$cachefile";
        if(file_exists($cachefile) && ($PHP_TIME < @filemtime($cachefile) + $CONFIG['phpcacheexpires']))
        {
            require $cachefile;
            exit;
        }
    }
    if($PHP_QUERYSTRING && preg_match("/^(.*)\.(htm|html|shtm|shtml)$/", $PHP_QUERYSTRING, $urlvar))
    {
        parse_str(str_replace(array('/', '-', ' '), array('&', '=', ''), $urlvar[1]));
    }
   
}

d.數據庫查詢結果緩存
下面是include/common.inc.php中的幾行代碼
$db_file = $db_class = 'db_'.$CONFIG['database']; //$CONFIG['database']位於config.inc.php中,配置可以使用自己的數據庫,如mysql,sqlite,sqlserver等
require PHPCMS_ROOT.'/include/'.$db_file.'.class.php';
$db = new $db_class;
$db->connect($CONFIG['dbhost'], $CONFIG['dbuser'], $CONFIG['dbpw'], $CONFIG['dbname'], $CONFIG['pconnect']);
$db->iscache = $CONFIG['dbiscache']; //是否啓用 sql cache (只對前臺起作用,建議在不生成html並且訪問量過大時開啓)
$db->expires = $CONFIG['dbexpires']; //sql cache 過期時間(秒)

db_mysql_cache.class.php中的代碼
function query($sql , $type = '' , $expires = 3600, $dbname = '')
    {
        if($this->isclient)
        {
            $dbname = $dbname ? $dbname : $this->dbname;
            $this->select_db($dbname);
        }
        /*
       
$this->iscache表示是否啓動了數據庫查詢緩存
        如果啓用了數據庫查詢緩存且$type爲CACHE且是select語句,則啓用查詢緩存
        個人感覺這兒$type參數用strtoupper處理一下更好了
        */
        if($this->iscache && $type == 'CACHE' && stristr($sql, 'SELECT'))
        {
            $this->caching = 1; //成員變量caching標識啓用了數據庫查詢緩存,用在下面的fetch_array,num_rows,free_result函數中,其實用iscache就可以判斷了,沒有必要再用一個成員變量了
            $this->expires = $expires; //數據庫緩存數據的失效期
            return $this->_query_cache($sql); //然後調用_query_cache方法
        }
        $this->caching = 0;
        $func = $type == 'UNBUFFERED' ? 'mysql_unbuffered_query' : 'mysql_query';
        if(!($query = $func($sql , $this->connid)) && $type != 'SILENT')
        {
            $this->halt('MySQL Query Error', $sql);
        }
        $this->querynum++;
        return $query;
    }

function _query_cache($sql)
    {
        $this->cache_id = md5($sql); //計算$sql的md5值,然後作爲cache_id
        $this->result = array();
        $this->cursor = 0;
        $this->cache_file = $this->_get_file(); //得到cache文件名
        //如果cache數據已經過期,則重新從數據庫中取得查詢結果,然後保存在數據庫中
        if($this->_is_expire())
        {
            $this->result = $this->_get_array($sql); //從數據庫中取結果
            $this->_save_result(); //保存結果到緩存數據中
        }
        else
        {
            $this->result = $this->_get_result(); //緩存沒過期直接取緩存數據
        }
        return $this->result;
    }

    function _get_file()
    {
        global $CONFIG;
        //cache文件的主目錄一般是data/dbcache
        return $CONFIG['dbcachedir'].substr($this->cache_id, 0, 2).'/'.$this->cache_id.'.php';
    }

function _is_expire()
    {
        global $PHP_TIME;
        return !file_exists($this->cache_file) || ( $PHP_TIME > @filemtime($this->cache_file) + $this->expires );
    }

/*
由於方法_get_array只是被方法_query_cache調用,所以在此方法裏面直接用函數mysql_unbuffered_query了,因爲mysql_unbuffered性能好一點,參考
http://bbs.chinaunix.net/viewthread.php?tid=958067&extra=page%3D4
*/
function _get_array($sql)
    {
        $this->cursor = 0;
        $arr = array();
        $result = mysql_unbuffered_query($sql, $this->connid);
        while($row = mysql_fetch_assoc($result))
        {
            $arr[] = $row;
        }
        $this->free_result($result);
        $this->querynum++;
        return $arr;
    }

function _save_result()
    {
        if(!is_array($this->result)) return FALSE;
        dir_create(dirname($this->cache_file));
        file_put_contents($this->cache_file, "<?php\n return ".var_export($this->result, TRUE).";\n?>");
        @chmod($this->cache_file, 0777);
    }

    function _get_result()
    {
         return include $this->cache_file;
    }

function fetch_array($query, $result_type = MYSQL_ASSOC)
    {
        return $this->caching ? $this->_fetch_array($query) : mysql_fetch_array($query, $result_type);
    }

//從數據庫中獲取查詢的結果
function _fetch_array($result = array())
    {
        if($result) $this->result = $result;
        return isset($this->result[$this->cursor]) ? $this->result[$this->cursor++] : FALSE;
    }

function num_rows($query)
    {
        return $this->caching ? $this->_num_rows($query) : mysql_num_rows($query);
    }

function free_result($query)
    {
        if($this->caching==1) $this->result = array();
        else @mysql_free_result($query);
    }

如果把上述的文件存儲改爲用memcached、eaccelerator、shm等來進行存儲的話效率會更高,改動起來也不是太難,後臺可以加一個設置選項,如分別是
文件,memcached,eaccelerator,shm等讓管理員進行設置,然後調用相應的存儲系統進行存儲


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章