PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > Smarty教程 > 正文

    smarty高级缓存的配置方法详解

    作者:w634381967来源:网络浏览:时间:2020-09-30 00:07:50我要评论
    导读:对于访问流量比较大、数据不需要及时更新的网站而言,充分使用缓存技术可以有效的减轻服务器压力。smarty模板引擎中也内置了功能强大的缓存
    对于访问流量比较大、数据不需要及时更新的网站而言,充分使用缓存技术可以有效的减轻服务器压力。smarty模板引擎中也内置了功能强大的缓存技术,只需要简单配置即可使用smarty的缓存功能。开启smarty高级缓存只需要在smarty的配置文件中设置好缓存存放的目录、开启缓存状态、设定缓存的有效期即可,具体使用方法如下:
     
    复制代码 代码如下:
    /***********smarty.php***********/
    <?php
    include ('./smarty/Smarty.class.php') ;//引入smarty模版引擎类
    $smarty=new Smarty;//实例化smarty对象
    $smarty->template_dir="templates";//指定模版存放目录
    $smarty->compile_dir="templates_c";//指定编译文件存放目录
    $smarty->config_dir="config";//指定配置文件存放目录
    $smarty->cache_dir="cache";//指定缓存存放目录
    $smarty->caching=true;//开启smarty缓存
    $smarty->cache_lifetime=60;//设定缓存的有效时间(单位:秒)
    $smarty->left_delimiter="<{";//指定左标签
    $smarty->right_delimiter="}>";//指定右标签
    ?>
    smarty高级缓存的使用方法实例
    /***********index.php   www.bcty365.com***********/
    <?php
    include ("smarty.php");
    date_default_timezone_set('PRC');
    $nowt=date('Y-m-d H:i:s');
    function insert_buhuancun(){//局部不缓存的内容(注意!此处insert_后面的方法名称要与模板文件中的对应)
    $ntime='B5教程网-'.date("Y-m-d H:m:s");
    return $ntime;
    }
    $smarty->assign('nowt',$nowt);
    $smarty->display("index.html");
    ?>
    /***********index.html***********/
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>B5教程网</title>
    </head>
    <body>
    此处内容将缓存60秒(即smarty.php配置文件中cache_lifetime所设定的时间):<font color='red'><{$nowt></font><br />
    insert局部数据不被缓存:<font color='red'><{insert name='buhuancun'}></font><br />
    block局部块不被缓存: <br />
    <font color='red'>
    <{block name='thisnocache' nocache}>
    &nbsp;&nbsp;包含在block块中的所有内容都不被缓存:<{$nowt}>
    <{/block}>
    </font><br />
    </body>
    </html>

    使用smarty高级缓存来缓存数据库中的某些内容也是一种不错的选择,不仅可以提高用户访问的速度,而且还可以减轻由于频繁访问数据库所带来的压力
    Smarty缓存的使用和清除
    $smarty->clear_all_cache(); //显然会把不想清的别的模板的缓存也给清空了。
    现在我在后台对这个带参数的页面basic.php?a=about 或=contact
    里所涉及到的东东进行修改更新数据库操作。当然这时候也要清空一下这个basic.tpl模板的所有缓存即缓存号为about和contact的两个缓存。

     
    复制代码 代码如下:
    // 清除某一模板的多个缓存中指定缓存号的一个
    $smarty->clear_cache("basic.tpl","about");
    $smarty->clear_cache("basic.tpl","contact");
    $smarty->display(‘cache.tpl’, cache_id); //创建带ID的缓存
    $smarty->clear_all_cache(); //清除所有缓存
    $smarty->clear_cache(‘index.htm’); //清除index.tpl的缓存
    $smarty->clear_cache(‘index.htm’,cache_id); //清除指定id的缓存

    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-84-1126-1.html
    相关热词搜索: Smarty缓存