《PHP教程:PHP文件緩存smarty模板應用實例分析》要點:
本文介紹了PHP教程:PHP文件緩存smarty模板應用實例分析,希望對您有用。如果有疑問,可以聯系我們。
本文實例分析了PHP文件緩存smarty模板應用.分享給大家供大家參考,具體如下:PHP實戰
一、使用緩存 PHP實戰
要開啟smarty的緩存,只需將caching設為true,并指定cache_dir即可.
使用cache_lefetime指定緩存生存時間,單位為秒
要對相同頁面生成多個不同的緩存,在display或fetch中加入第二參數cache_id,如:PHP實戰
$smarty->display('index.tpl',$my_cache_id);
此特性可用于對不同的$_GET進行不同的緩存
?
二、清除緩存PHP實戰
clear_all_cache();//清除所有緩存 clear_cache('index.tpl');//清除index.tpl的緩存 clear_cache('index.tpl',cache_id);//清除指定id的緩存
三、使用自定義緩存方式PHP實戰
設置cache_handler_func使用自定義的函數處理緩存
如:PHP實戰
$smarty->cache_handler_func = "myCache"; function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null){ }
該函數的一般是根椐$action來判斷緩存當前操作:PHP實戰
switch($action){ case "read"://讀取緩存內容 case "write"://寫入緩存 case "clear"://清空 }
一般使用md5($tpl_file.$cache_id.$compile_id)作為唯一的cache_id
如果需要,可使用gzcompress和gzuncompress來壓縮和解壓
?
四、局部關閉緩存PHP實戰
要在某些區域使緩存失效(只對需要的緩存),有幾種辦法:PHP實戰
insert:PHP實戰
定義一個insert標簽要使用的處理函數,函數名格式為:insert_xx(array $params, object &$smarty)其中的xx是insert的name,也就是說,如果你定義的函數為insert_abc,則模板中使用辦法為{insert name='abc'}PHP實戰
參數通過$params傳入PHP實戰
也可以做成insert插件,文件名命名為:insert.xx.php,函數命名為:smarty_insert_aa($params,&$smarty),xx定義同上PHP實戰
register_block:PHP實戰
定義一個block:
PHP實戰
smarty_block_name($params,$content, &$smarty){return $content;} //name表示區域名
注冊block:PHP實戰
$smarty->register_block('name', 'smarty_block_name', false); //第三參數false表示該區域不被緩存
模板寫法:PHP實戰
{name}內容{/name}
寫成block插件:PHP實戰
1)定義一件插件函數:block.cacheless.php,放在smarty的plugins目錄
block.cacheless.php的內容如下:PHP實戰
<?php function smarty_block_cacheless($param, $content, &$smarty) { return $content; } ?>
2) 編寫程序及模板PHP實戰
示例程序:testCacheLess.phpPHP實戰
<?php include('Smarty.class.php'); $smarty = new Smarty; $smarty->caching=true; $smarty->cache_lifetime = 6; $smarty->display('cache.tpl'); ?>
所用的模板:cache.tplPHP實戰
已經緩存的: {$smarty.now}<br> {cacheless} 沒有緩存的: {$smarty.now} {/cacheless}
更多關于PHP相關內容感興趣的讀者可查看本站專題:《smarty模板入門基礎教程》、《php日期與時間用法總結》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》PHP實戰
希望本文所述對大家PHP程序設計有所贊助.PHP實戰
維易PHP培訓學院每天發布《PHP教程:PHP文件緩存smarty模板應用實例分析》等實戰技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養人才。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/7503.html