将前台后台隔离,前台控制显示,后台控制逻辑/内容,与cms类似
原理: 用户访问text.php页面,后台调用类smarty.class.php显示静态模板;
临时文件:
在不改变模板内容的情况下,再次访问页面,直接从临时文件获取,不走smarty.class.php,提高加载速度;当改变了模板内容,就得从头来过。
缓存文件:
相比临时文件,里面放的是html文件,运行效率更快;一般需设置有效期,不设置的话,当数据库内容改变时,再次刷新页面,页面显示内容无变化,因为执行的是缓存。
smarty.class.php(核心):
<?php class Smarty { public $left="<{"; //左分隔符 public $right="}>"; //右分隔符 public $attr=array(); //存储变量 //注册变量 function assign($name,$value) { $this->attr[$name]->$value; } //显示模板 function display($filename){ //获取静态文件内容 $str=file_get_contents($filename); /*<html> <head></head> <body> <div><{aa}></div> </body> </html> */ //得到结果 //正则表达式匹配内容,aa,查找和替换 /*<html> <head></head> <body> <div><?php echo $attr["aa"] ?></div> </body> </html> */ //得到结果 //将替换后的内容存到临时文件 $lujing="../text/docunment.php"; file_put_contents($lujing,$str); //读取临时文件 include ($lujing); } }
配置文件int.inc.php(核心):
<?php define("ROOT",str_replace("\","/",dirname(__FILE__)).'/'); //常量ROOT中指定项目根目录 //echo str_replace("\","/",dirname(__FILE__)).'/'; //获取当前文件所在的位置 require ROOT.'libs/Smarty.class.php'; //加载Smarty类文件 $smarty = new Smarty(); //实例化Smarty对象 //$smarty -> auto_literal = false; //就可以让定界符号使用空格 $smarty->setTemplateDir(ROOT.'templates/'); //设置所有模板文件存放位置 //$smarty->addTemplateDir(ROOT.'templates2/'); //添加一个模板文件夹 $smarty->setCompileDir(ROOT.'templates_c/'); //设置编译过的模板存放的目录 $smarty->addPluginsDir(ROOT.'plugins/'); //设置为模板扩充插件存放目录 $smarty->setCacheDir(ROOT.'cache/'); //设置缓存文件存放目录 $smarty->setConfigDir(ROOT.'configs/'); //设置模板配置文件存放目录 $smarty->caching = false; //设置Smarty缓存开关功能 $smarty->cache_lifetime = 60*60*24; //设置缓存模板有效时间一天 $smarty->left_delimiter = '<{'; //设置模板语言中的左结束符 $smarty->right_delimiter = '}>'; //设置模板语言中的右结束符 ?>
main.php:
<?php include("../init.inc.php"); $smarty->assign("aa","hello"); $smarty->display("test.html")