php smarty 緩衝施用

來源:互聯網
上載者:User
php smarty 緩衝使用

一、使用緩衝

?

要開啟smarty的緩衝,只需將caching設為true,並指定cache_dir即可.
使用cache_lefetime指定 緩衝存留時間,單位為秒
要對相同頁面產生多個不同的緩衝,在display或fetch中加入第二參數cache_id, 如$smarty->display('index.tpl',$my_cache_id);此特性可用於對不同的$_GET進行不同的緩衝

?

二、清除緩衝


clear_all_cache();//清除所有緩衝
clear_cache('index.tpl');// 清除index.tpl的緩衝
clear_cache('index.tpl',cache_id);//清除指定id的緩衝


三、使用自訂緩衝方式


設定cache_handler_func使用自訂的函數處理緩衝
如:
$smarty->cache_handler_func = "myCache";
function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null){
}
該 函數的一般是根椐$action來判斷緩衝當前操作:
switch($action){
case "read"://讀取緩衝內容
case "write"://寫入緩衝
case "clear"://清空
}
一般使用 md5($tpl_file.$cache_id.$compile_id)作為唯一的cache_id
如果需要,可使用gzcompress和 gzuncompress來壓縮和解壓

?

四、局部關閉緩衝


要在某些地區使緩衝失效(只對需要的緩衝),有幾種方法:
inser:
定 義一個inser標籤要使用的處理函數,函數名格式為:insert_xx(array $params, object &$smarty)其中的xx是insert的name,也就是說,如果你定義的函數為insert_abc,則模板中使用方法為{insert name='abc'}
參數通過$params傳入
也可以做成insert外掛程式,檔案名稱命名為:insert.xx.php,函數命名 為:smarty_insert_aa($params,&$smarty),xx定義同上
register_block:
定 義一個block:smarty_block_name($params,$content, &$smarty){return $content;} //name表示地區名
註冊block:$smarty->register_block('name', 'smarty_block_name', false); //第三參數false表示該地區不被緩衝
模板寫法:{name}內容 {/name}

寫成block外掛程式:
1)定義一件外掛程式函數:block.cacheless.php,放在smarty的plugins目錄
block.cacheless.php 的內容如下:

function smarty_block_cacheless($param, $content, &$smarty) {
return $content;
}
?>

2) 編寫程式及模板
樣本程式:testCacheLess.php

include('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching=true;
$smarty->cache_lifetime = 6;
$smarty->display('cache.tpl');
?>


所用的模 板:cache.tpl

已經緩衝的:{$smarty.now}

{cacheless}
沒有緩 存的:{$smarty.now}
{/cacheless}

現在運行一下,發現是不起作用的,兩行內容都被緩衝了
3)改寫Smarty_Compiler.class.php(注:該檔案很重 要,請先備份,以在必要時恢複)
尋找$this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true); //我的在705行
修改成:
if($tag_command == 'cacheless') $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, false);
else $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true);

你也可以直接將原句的最後一個參數改成false,我對smarty的內部機制不太瞭解,所以加了一個判斷,只要block是 cacheless的才不作緩衝

4)OK,現在清除template_c裡的編譯檔案,重新運行,起作用了吧?

?

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.