推荐:适合程序员的模版类(采用缓存)

字体大小: 中小 标准 ->行高大小: 标准
最近自己在写一个系统,懒得学习sm 和pl而且我觉得也没必要扛那么大的一门炮,所以借鉴DZ写了一个模版类。
功能:条件判断、foreach 循环、for循环、计算好的函数直接放到模版无需在编译(我比较懒,这个也是我写这个模版类的原因)、直接在模版中调用任何php内置函数或自定义函数。模版采用缓存
  1. <?php
  2. /* 村民:52php */
  3. /* mail: insuns@gmail.com */
  4. /* 2007- 4 -5 */
  5. class Template{

  6. var $tpl_data = '';
  7. var $root = ''; //模版对网站根地址的路径,比如‘.'或者'./../’;
  8. var $tpl_dir = 'templates';//模版文件夹
  9. var $cache_dir = 'cache'; //模版缓存文件夹
  10. var $flush = 12; ///12个小时更新一次
  11. var $files = '';
  12. var $ext = '.html'; //模版文件的后缀名

  13. function Template($root)
  14. {
  15. $this->root = $root;
  16. }

  17. function parse($files)
  18. {
  19. $this->files = $this->root . $this->tpl_dir . '/' . $files . $this->ext;
  20. $this->cache = $this->root . $this->cache_dir . '/' . $files.'.php';

  21. if(@file_exists($this->cache)) //cache文件存在
  22. {
  23. $fmtime = @filemtime($this->cache); //检查cache的修改时间
  24. if(($fmtime + $this->flush * 3600) < time()) //cache过时则重建并返回
  25. {
  26. return $this->write_to_cache($this->files);
  27. }
  28. else return $this->cache;
  29. }
  30. else //cache不存在则直接编译模版
  31. {
  32. return $this->write_to_cache($this->files);
  33. }
  34. }

  35. function update($files)
  36. {
  37. $this->flush = 0;
  38. if(is_array($files))
  39. {
  40. list($key,$handle) = each($files);
  41. $this->parse($handle);
  42. }
  43. else $this->parse($files);
  44. }

  45. function write_to_cache($files)
  46. {
  47. $this->tpl_data = $this->compiled($files);
  48. $state = @file_put_contents($this->cache,$this->tpl_data,LOCK_EX);
  49. if (!$state) die('写入模版 '.$this->files.' 的缓存文件时失败,请检查相应目录及文件的属性!<br>'.$this->cache);
  50. else return $this->cache;
  51. }

  52. function compiled($files)
  53. {
  54. $data .= '<?php if(!defined(\'IN_INSUN\'))'."\t".'die("Hacking attempt!");?>'."\n";
  55. if (!$temp = @file($files)) die('Failed to open template file '.$files);
  56. $data .= implode('',$temp);
  57. $data = preg_replace('/\{(\$.+?)\}/',"<?=\\1;?>",$data);
  58. $data = preg_replace('/\{LOOP\_FOR\s([\$a-zA-Z]+)\=([\d]+)\scount\((.+)\)\}/','<? for (\\1=\\2;\\1<count(\\3);\\1++){ ?>',$data);
  59. $data = preg_replace('/\{LOOP\s(\$.+?)\s(\$.+?)\}/','<? foreach(\\1 as \\2) {?>',$data);
  60. $data = str_replace(array('{/LOOP_FOR}','{/LOOP}'),'<? }?>',$data);
  61. $data = preg_replace('/\{FUN\s(.+?)\}/',"<?=\\1;?>",$data);
  62. $data = preg_replace('/\{(ELSE)?IF\s(.+?)}/','<? \\1IF(\\2) {?>',$data);
  63. $data = str_replace(array('{ELSE}','{/IF}'),array('<? } ELSE { ?>','<? }?>'),$data);

  64. return $data;
  65. }
  66. }

  67. ?>
复制代码
使用示例:
以后台./admin/index.php的调用为例,
./admin/index.php
  1. <?php
  2. define('IN_INSUN',1);

  3. ///以下的$test函数为测试函数,当然你可以把你计算完的任何函数放到模版中不用进行其他的换算
  4. $test = 'This just a test template';
  5. $url = 'http://163.com';

  6. /////以下调用模版类进行编译
  7. $admin_root_path = './../'; //定义后台对跟目录的路径
  8. $admin_tpl_dir = 'admin/'; ///后台模板缓存文件夹
  9. require_once './../my_class/template.php';
  10. $tp = new Template($admin_root_path);
  11. include $tp->parse($admin_tpl_dir.'test'); //引入后台首页模板
  12. ?>
复制代码
以下是模版./templates/index.html
  1. <html>
  2. <head>
  3. <title>test template</title>
  4. </head>
  5. <body>
  6. <div style="position:absolute;top:30%;left:10%;right:10%;font-size:28px;font-weight:bold">{$test}<br/>这个是调用htmlspecialchars 函数示例,你可以调用任何php函数或者自定义函数。但为了区别你通过赋值或计算的变量,需在{后面加上大写的FUN如:{FUN htmlspecialchars($url)}</div>
  7. </body>
  8. </html>
复制代码
调用说明
变量:在模版中用 {变量}
函数:在模版中用{FUN 函数}
条件判断:{IF 条件} 。。。{ELSEIF 条件} 。。。{ELSE} 。。。{/IF}
for循环:{LOOP_FOR 初始值 最大值}循环体{/LOOP}
foreach循环:{LOOP 原始变量 foreach后的变量} 循环体{/LOOP}

以下是我一个模版实体部分的调用,除了for循环外其他的调用都有,大家看下,有不清楚的留言:
  1. <div id="wrap">
  2. <form action="" method="post" name="form1">
  3. <table border="0" width="96%" align="center">
  4. <tr class="{FUN getbg()}">
  5. <td colspan="10" align="right">
  6. <table width="100%" align="center" border="0">
  7. <tr>
  8. <td>
  9. <a href="index.php?action={$archive_table[$channel_id].'_manage'}&amp;do=add&amp;channel_id={$channel_id}">添加文档</a>
  10. </td>
  11. <td>
  12. <a href="index.php?action={$archive_table[$channel_id].'_manage'}&amp;do=validate&amp;channel_id={$channel_id}">审核</a>
  13. </td>
  14. </tr>
  15. </table>
  16. </td>
  17. </tr>

  18. {IF $channel_id == '3'}
  19. <tr class="{FUN getbg()}" align="center">
  20. <td width="5%"><strong>ID</strong></td>
  21. <td width="5%"><strong>选择</strong></td>
  22. <td width="20%"><strong>歌名</strong></td>
  23. <td width="9%"><strong>分类</strong></td>
  24. <td width="9%"><strong>专辑</strong></td>
  25. <td width="9%"><strong>歌手</strong></td>
  26. <td width="5%"><strong>点击数</strong></td>
  27. <td width="10%"><strong>创建时间</strong></td>
  28. <td width="10%"><strong>修改时间</strong></td>
  29. <td width="18%"><strong>操作</strong></td>
  30. </tr>
  31. {LOOP $rows $arc}
  32. <tr class="{FUN getbg()}" align="center">
  33. <td>{$arc['music_id']}</td>
  34. <td><input type="checkbox" name="arcid" id="arcid" value="{$arc['music_id']}"/></td>
  35. <td><a href="index.php?action=music_manage&amp;do=edit&amp;music_id={$arc['music_id']}">{$arc['title']}</a></td>
  36. <td>{$arc['name']}</td>
  37. <td>{$arc['album_name']}</td>
  38. <td>{$arc['singer_name']}</td>
  39. <td>{$arc['click']}</td>
  40. <td>{$arc['post_time']}</td>
  41. <td>{$arc['last_update']}</td>
  42. <td><a href="{$insun_root_path.$channel_id.'/'.$cat_id.'/'.$arc['music_id'].EXT}">浏览文档</a> | <a href="index.php?action=music_manage&amp;do=edit&amp;music_id={$arc['music_id']}">编辑</a> | <a href="index.php?action=music_manage&amp;do=del&amp;music_id={$arc['music_id']}&amp;name={FUN urlencode($arc['title'])}">删除</a></td>
  43. </tr>
  44. {/LOOP}
  45. {/IF}
  46. {IF $totalPage>=1}
  47. <tr class="{FUN getbg()}">
  48. <td colspan="10" align="center">{$page_nav}</td>
  49. </tr>
  50. {/IF}
  51. {IF $rows[0]['name']}
  52. <tr class="{FUN getbg()}">
  53. <td colspan="10">
  54. <input type="radio" name="action" value="recommend" />推荐
  55. <input type="radio" name="action" value="move" />移动
  56. <input type="radio" name="action" value="del" />删除
  57. <input type="button" onclick="CheckAll(this.form)" class="submit little" value="全选">
  58. <input type="button" name="submit" onclick="CheckOthers(this.form)" class="submit little" value="反选">
  59. <input type="submit" value="Submit" class="submit little" />
  60. </td>
  61. </tr>
  62. {ELSE}
  63. <tr class="{FUN getbg()}">
  64. <td colspan="10" align="center">目前尚无文档!</td>
  65. </tr>
  66. {/IF}
  67. </table>

  68. </form>
  69. </div>
复制代码
 
for循环调用示例:
  1. {LOOP_FOR $i=0 count($test)}
  2. <li>$test</li>
  3. {/LOOP}
复制代码
模版缓存更新请调用update 如:$tp->update($admin_tpl_dir.'test');
update中的文件可以是array,需要注意的是路径问题,如果后台模版是在./templates/admin/,那么后台调用模版文件就要用admn/file.html
这个用的比较少,所以各位如果需要用到请自己测试。

这个模版并不适合美工用,因为我是自己写程序和模版,所以只为方便写的,没考虑通用性,我考虑的是实用性和方便。当然,因为我的系统并没写完,所以功能上增减也是必然。如果发现bug请报告给我,谢谢
不好意思,事例中的:$admin_tpl_dir = 'admin/'; ///后台模板缓存文件夹 错了。这个应该是$admin_tpl_dir = 'admin/'; ///后台模板文件夹 也就是后台模版对模版文件夹的地址,如果你是所有的模版都放在一起的就不用定义
  1. <?php
  2. define('IN_INSUN',1);

  3. ///以下的$test函数为测试函数,当然你可以把你计算完的任何函数放到模版中不用进行其他的换算
  4. $test = 'This just a test template';
  5. $url = 'http://163.com';

  6. /////以下调用模版类进行编译
  7. $admin_root_path = './../'; //定义后台对跟目录的路径
  8. $admin_tpl_dir = 'admin/'; ///后台模板文件夹
  9. require_once './../my_class/template.php';
  10. $tp = new Template($admin_root_path);
  11. include $tp->parse($admin_tpl_dir.'test'); //引入后台首页模板
  12. ?>

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/29866.html