smarty中删除缓存的方法

Posted by admin on 2012, May 26

同时,smarty也提供了一个清除缓存的function(实质是使缓存文件过期,并非删除缓存文件)

我们发现可以使用:

  1. function clear_cache($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null)删除某个具体的模板。如主页,某条信息。
  2. function clear_all_cache($exp_time = null)删除缓存目录下所有所有缓存信息。

然而很多人,也包括我,一开始对怎么清理所有内容页(即show.php?id=1 …. 198 ….)的所有缓存文件产生了疑问。clear_cache()显然不适用,而clear_all_cache呢?似乎后者会把index.php等其它页面的缓存文件也清除。

在这里提提大家,看到我对function clear_all_cache()划线部分的标注。 clear_all_cache是把缓存目录下的所有文件清理掉。所以如果我们把show.php?id=1….134…的缓存文件都放在一个show的目录下,在执行clear_all_cache的时候,先设置cache_dir的路径为show,似乎一切就可行了,而事实上也是这样。

如我在项目中的一个使用:

渲染模板到show目录下:

[php] view plaincopy

  1. <?php
  2. header(“HTTP/1.0 200 OK”);
  3. require_once ‘includes/common.php’;
  4. $smarty = new CustomSmarty();
  5. $smarty->cache_dir = $smarty->cache_dir.”/show”;
  6. $smarty->caching = true;
  7. $key = $_GET[‘key’];
  8. if(!$smarty->is_cached(‘page.html’,$key))
  9. {
  10. #code here
  11. }
  12. $smarty->display(‘page.html’,$key);
  13. ?>

清理show目录下的缓存:

[php] view plaincopy

  1. <?php
  2. require_once dirname(FILE).’/../../includes/common.php’;
  3. $smarty = new CustomSmarty();
  4. $smarty->caching = false;
  5. $smarty->cache_dir = $smarty->cache_dir.”/show”;
  6. $smarty->clear_all_cache();
  7. $smarty->assign(“title”,”更新内容页缓存”);
  8. $smarty->display(“admin/recache/index.html”);
  9. ?>