IT技术博客大学习 共学习 共进步

Smarty之缓存操作

Penner Blog 2009-10-16 12:04:42 浏览 3,664 次

    一、使用缓存

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

    使用cache_lefetime指定缓存生存时间,单位为秒,要对相同页面生成多个不同的缓存,在display或fetch中加入第二参数cache_id,如:

//此特性可用于对不同的$_GET进行不同的缓存

    $smarty->display(\'index.tpl\',$my_cache_id);

    二、清除缓存

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}

建议继续学习

  1. 浅析http协议、cookies和session机制、浏览器缓存 (阅读 17,204)
  2. 分布式缓存系统 Memcached 入门 (阅读 16,044)
  3. 强制刷新本地 DNS 缓存记录 (阅读 10,642)
  4. php缓存与加速分析与汇总 (阅读 7,723)
  5. Web应用的缓存设计模式 (阅读 7,304)
  6. 浏览器缓存机制 (阅读 7,102)
  7. 使用memc-nginx和srcache-nginx构建高效透明的缓存机制 (阅读 6,943)
  8. 谈冷热数据 (阅读 6,884)
  9. 缓存设计的一些思考 (阅读 6,823)
  10. 系统架构的一些思考 (阅读 6,682)