盘大叔叔logo

自己写的超简单的PHP模板引擎—基于文件读写—以留言板实现功能

2011年01月20日     / 0评 / 0

    最近发生了一些事,也让我静下心来专心学习了,下面只是初学PHP的一点应用,当作笔记。

    以一个简单的留言板为功能,基于文件读写的模板,算不上引擎的引擎,只是讲讲原理哈  

    主要描述:以留言板为功能框架基础,程序逻辑与美工分离,实现静态html文件

    文件目录很简单:./index.php——用于生成首页文件  ./conn.php——数据库连接文件  ./template/——用于存放模板文件目录   ./template/index.htm——首页模板文件  ./index.html——最终生成静态页

    主要思想:由核心逻辑程序文件读取模板文件,然后碰到特殊标签进行替换,如{title}替换为程序里面具有意义的$title变量,最后将替换好的代码生成为最终的html静态文件

    主要用到的:文件读写函数(fopen($filename, $mode)   fread($handle, $length)   fwrite($handle, $string) 等)正则表达式  字符串处理函数  当然还有数据库的一些操作函数

    程序清单:
    ./template/index.htm——首页模板文件

<html>
 <head> 
  <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> 
  <title>{title}</title> 
 </head> 
 <body style="background:#EFEFEF; width:950px margin:0 auto;">
   &nbsp;{moudle message 0,5} &nbsp;&nbsp;
  <table border="0" cellspacing="0" cellpadding="2" width="300px" align="center">
    &nbsp;&nbsp;&nbsp;
   <tbody>
    <tr bgcolor="#AAAAAA">
     <td width="50px">用户:</td>
     <td>{user}</td>
    </tr> &nbsp;&nbsp;&nbsp;
    <tr bgcolor="#EEEEEE">
     <td>标题:</td>
     <td>{mtitle}</td>
    </tr> &nbsp;&nbsp;&nbsp;
    <tr bgcolor="#EEEEEE">
     <td>时间:</td>
     <td>{mtime}</td>
    </tr> &nbsp;&nbsp;&nbsp;
    <tr bgcolor="#EEEEEE">
     <td>内容:</td>
     <td>{mcontent}</td>
    </tr> &nbsp;&nbsp;
   </tbody>
  </table> &nbsp;{/moudle message}  
 </body>
</html>

 ./index.php——首页核心程序逻辑文件

<?php
include_once("conn.php");
$title="小盘留言板系统";
$template="template/";
$fp=fopen($template."index.htm","r"); //只读模式打开
$str=fread($fp,filesize($template."index.htm"));
$str=str_replace("{title}", $title, $str);

ereg("\{moudle[[:blank:]]+[a-zA-Z]+[[:blank:]]+[[:alnum:]]+,+[[:alnum:]]\}", $str,$s);  //得到模板中的模块
$mstr=explode('}', $s[0]);  //去除右侧大括号
$mstr=explode(' ', $mstr[0]);  //对模块名称进行切割
$module=$mstr[1];   //得到当前模块名称
//echo "当前的模块是$module<br>";
$var=explode(',',$mstr[2]);  //得到当前参数

switch($module){
 case "message":
  $sql="select * from message order by id desc LIMIT $var[0],$var[1]";
  break;
 default:
  echo "未知模块,请检查....";
}
$query=mysql_query($sql);
ereg("\{moudle message (.*)\{/moudle message\}", $str,$code_str);
$code_str2=$code_str[0];
$code_str=$code_str[0];
ereg('\{/moudle +[a-zA-Z]+\}', $code_str,$s2);
$code_str=str_replace($s2[0],'',str_replace($s[0],'', $code_str));  //将模块{module ***}标识去掉
$code='';
while($row=mysql_fetch_array($query))
{
 $code_str=str_replace('{user}', $row[user], $code_str);
 $code_str=str_replace('{mtitle}', $row[title], $code_str);
 $code_str=str_replace('{mtime}', $row[lastdate], $code_str);
 $code_str=str_replace('{mcontent}', $row[content], $code_str);
 $code=$code.$code_str;
}

//echo $code;
fclose($fp);

$str=str_replace($code_str2,$code,$str);

$handle=fopen("index.html","w");
fwrite($handle, $str);
fclose($handle);
//echo "生成成功!";
?>
鲁ICP备2021023915号