PHP模版引擎之Smarty的缓存操作技巧

开发 后端
本文介绍的是PHP引擎模版Smarty的缓存的一些操作技巧。希望对你有帮助,一起来看吧!

我们知道PHP语言作为开源社区的一员,提供了各种模板引擎,如FastTemplate,Smarty,SimpleTemplate等,而Smarty是现在使用得比较多的PHP模板引擎,下面介绍Smarty的缓存操作技巧。

一、使用缓存

要开启smarty的缓存,只需将caching设为true,并指定cache_dir即可.

使用cache_lefetime指定缓存生存时间,单位为秒

要对相同页面生成多个不同的缓存,在display或fetch中加入第二参数cache_id,如$smarty->display('index.tpl',$my_cache_id);此特性可用于对不同的$_GET进行不同的缓存

二、清除缓存

  1. clear_all_cache();//清除所有缓存  
  2. clear_cache('index.tpl');//清除index.tpl的缓存  
  3. clear_cache('index.tpl',cache_id);//清除指定id的缓存 

三、使用自定义缓存方式

设置cache_handler_func使用自定义的函数处理缓存
如:

  1. $smarty->cache_handler_func = "myCache";  
  2. function myCache($action, &$smarty_obj, &$cache_content$tpl_file=null, 
  3. $cache_id=null, $compile_id=null)  
  4. {  

该函数的一般是根椐$action来判断缓存当前操作:

  1. switch($action){  
  2. case "read"://读取缓存内容  
  3. case "write"://写入缓存  
  4. case "clear"://清空  

一般使用md5($tpl_file.$cache_id.$compile_id)作为唯一的cache_id

如果需要,可使用gzcompress和gzuncompress来压缩和解压

四、局部关闭缓存

要在某些区域使缓存失效(只对需要的缓存),有几种方法:

insert:

定义一个insert标签要使用的处理函数,函数名格式为:

  1. insert_xx(array $params, object &$smarty

其中的xx是insert的name,也就是说,如果你定义的函数为insert_abc,则模板中使用方法为

  1. {insert name='abc'

参数通过$params传入

也可以做成insert插件,文件名命名为:insert.xx.php,函数命名为:smarty_insert_aa($params,&$smarty),xx定义同上

register_block:

定义一个

  1. block:  
  2. smarty_block_name($params,$content, &$smarty)  
  3. {  
  4. return $content;  
  5. //name表示区域名 

注册

  1. block:$smarty->register_block('name''smarty_block_name', false);   
  2. //第三参数false表示该区域不被缓存 

模板写法:{name}内容{/name}

写成block插件:

1)定义一件插件函数:block.cacheless.php,放在smarty的plugins目录

block.cacheless.php的内容如下:

  1. <?php  
  2. function smarty_block_cacheless($param$content, &$smarty) {  
  3. return $content;  
  4. }  
  5. ?> 

2) 编写程序及模板

示例程序:testCacheLess.php

  1. <?php  
  2. include('Smarty.class.php');  
  3. $smarty = new Smarty;  
  4. $smarty->caching=true;  
  5. $smarty->cache_lifetime = 6;  
  6. $smarty->display('cache.tpl');  
  7. ?> 

所用的模板:cache.tpl

已经缓存的

  1. {$smarty.now}<br>  
  2. {cacheless} 

没有缓存的:

  1. {$smarty.now}  
  2. {/cacheless} 

到这,就给大家介绍完了。建议大家看看这两篇文章,《PHP模板之Smarty教程》和《详细介绍PHP模板引擎Smarty》,供大家参考。

【编辑推荐】

  1. 让PHP网站跑的更快 如何优化PHP
  2. 警惕 PHP程序员最易犯10种错误
  3. 高效PHP程序必知的53个技巧
  4. PHP爱好者请坚定你们的信念!
  5. 提高PHP速度的几种办法

 

责任编辑:于铁 来源: 大家论坛
相关推荐

2011-07-07 16:15:20

Smarty

2011-07-07 13:48:35

Smarty

2011-05-19 11:03:02

PHPDwoo

2009-12-01 19:23:22

PHP缓存技术

2011-05-19 10:39:12

2009-11-30 13:15:27

PHP模板Smarty

2009-12-10 17:27:39

PHP操作Cookie

2021-02-15 12:11:00

开发技巧

2009-03-04 10:53:39

gettextsmartyphp

2009-12-10 15:41:35

PHP文件操作

2009-12-10 16:35:08

PHP操作文章列表

2015-09-09 10:20:00

php缓存技术

2009-11-23 17:56:44

PHP缓存机制

2011-07-15 14:01:50

PHP模板引擎

2021-06-16 08:56:06

模版方法模式设计模式行为型设计模式

2009-12-02 13:53:12

PHP使用技巧

2009-12-04 10:19:11

PHP hack

2011-03-11 15:53:00

LAMP优化

2020-02-19 20:24:35

PHP缓存静态

2020-11-06 00:00:00

PHP技巧后门
点赞
收藏

51CTO技术栈公众号