PHP头条
热点:

五、DWOO中的缓存

Dwoo中已经内置了很好的缓存功能,大大提高了效率,下面讲解使用dwoo缓存的步骤:

1. 在Dwoo_Template_File的构造函数中,设定cache的名称和缓存时间。

2. 在isCached()方法中,编写相关的模版生成代码,并且当缓存存在的时候,直接返回缓存中的页面。

下面举一个搜索Twitter中信息的例子来说明如何使用缓存:

  1. <html> 
  2. <head> 
  3. <style type="text/css">...  
  4. div.outer {...}{  
  5. border-bottom: dashed orange 1px;  
  6. padding: 4px;  
  7. clear: both;  
  8. height: 50px;  
  9. }   
  10. div.img {...}{  
  11. float:left;  
  12. padding-right: 2px;  
  13. }  
  14. span.attrib {...}{  
  15. font-style: italic;  
  16. }  
  17. </style>   
  18. </head> 
  19. <body> 
  20. <h2>{$title}</h2> 
  21. {loop $records}  
  22. <div class="outer"> 
  23. <div class="img"><img width=48" height="48" src="{$image}" /></div> 
  24. <div>{$tweet} <br/> <span class="attrib">By <a href="{$uri}">{$owner}</a> on {$time}</span></div> 
  25. </div>   
  26. {/loop}  
  27. </body> 
  28. </html> 

上面的模版是循环输出在Twitter中检索输出的微博内容。接下来看处理模版的PHP程序,如下:

  1. <?php  
  2. include 'dwooAutoload.php';  
  3. $dwoo = new Dwoo();  
  4. $tpl = new Dwoo_Template_File('tmpl/tweets.tpl', 120, 'id_g75430i472j');  
  5. //检查缓存中是否已经存在该文件,存在的话,从缓存中显示  
  6. if ($dwoo->isCached($tpl)) {  
  7. $dwoo->output($tplarray());  
  8. echo '(cached output)';  
  9. else {  
  10. //缓存中不存在,直接搜索twitter   
  11. $result = simplexml_load_file('http://search.twitter.com/search.atom?q=pasta&lang=en');  
  12. $records = array();  
  13. foreach ($result->entry as $entry) {  
  14. $item['image'] = (string)$entry->link[1]['href'];   
  15. $item['owner'] = (string)$entry->author->name;  
  16. $item['uri'] = (string)$entry->author->uri;  
  17. $item['tweet'] = (string)$entry->content;  
  18. $item['time'] = date('d M Y, h:i'strtotime($entry->published));   
  19. $records[] = $item;  
  20. }  
  21. $data = new Dwoo_Data();  
  22. $data->assign('records'$records);  
  23. $data->assign('title'$result->title);  
  24. $dwoo->output($tpl$data);   

上面的PHP代码中,首先是用isCached()方法,判断缓存中是否有该文件,如果有的话则直接读取缓存中已经合成好的页面文件显示给用户,否则的话调用twitter的Atom公开API接口去查询关键字pasta,再输出到页面。输出结果如下图:

shuchujieguo

同时注意,$tpl = new Dwoo_Template_File('tmpl/tweets.tpl', 120, 'id_g75430i472j');中,第2个参数是缓存的过期时间,为120秒,第3个参数是缓存的名称,而且该名称在应用中必须是唯一的。


www.phpzy.comtrue/php/9245.htmlTechArticle五、DWOO中的缓存 Dwoo中已经内置了很好的缓存功能,大大提高了效率,下面讲解使用dwoo缓存的步骤: 1. 在Dwoo_Template_File的构造函数中,设定cache的名称和...

相关文章

相关频道:

PHP之友评论

今天推荐