设为首页 收藏本站
查看: 446|回复: 0

[经验分享] 一个PHP Template

[复制链接]

尚未签到

发表于 2017-3-22 08:32:15 | 显示全部楼层 |阅读模式

  • <?php
  • class Template {
  •   var $classname = "Template";
  •   /* if set, echo assignments */
  •   var $debug     = false;
  •   /* $file[handle] = "filename"; */
  •   var $file  = array();
  •   /* relative filenames are relative to this pathname */
  •   var $root   = "";
  •   /* $varkeys[key] = "key"; $varvals[key] = "value"; */
  •   var $varkeys = array();
  •   var $varvals = array();
  •   /* "remove"  => remove undefined variables
  •    * "comment" => replace undefined variables with comments
  •    * "keep"    => keep undefined variables
  •    */
  •   var $unknowns = "remove";
  •   
  •   /* "yes" => halt, "report" => report error, continue, "no" => ignore error quietly */
  •   var $halt_on_error  = "yes";
  •   
  •   /* last error message is retained here */
  •   var $last_error     = "";
  •   /***************************************************************************/
  •   /* public: Constructor.
  •    * root:     template directory.
  •    * unknowns: how to handle unknown variables.
  •    */
  •   function Template($root = ".", $unknowns = "remove") {
  •     $this->set_root($root);
  •     $this->set_unknowns($unknowns);
  •   }
  •   /* public: setroot(pathname $root)
  •    * root:   new template directory.
  •    */  
  •   function set_root($root) {
  •     if (!is_dir($root)) {
  •       $this->halt("set_root: $root is not a directory.");
  •       return false;
  •     }
  •     
  •     $this->root = $root;
  •     return true;
  •   }
  •   /* public: set_unknowns(enum $unknowns)
  •    * unknowns: "remove", "comment", "keep"
  •    *
  •    */
  •   function set_unknowns($unknowns = "keep") {
  •     $this->unknowns = $unknowns;
  •   }
  •   /* public: set_file(array $filelist)
  •    * filelist: array of handle, filename pairs.
  •    *
  •    * public: set_file(string $handle, string $filename)
  •    * handle: handle for a filename,
  •    * filename: name of template file
  •    */
  •   function set_file($handle, $filename = "") {
  •     if (!is_array($handle)) {
  •       if ($filename == "") {
  •         $this->halt("set_file: For handle $handle filename is empty.");
  •         return false;
  •       }
  •       $this->file[$handle] = $this->filename($filename);
  •     } else {
  •       reset($handle);
  •       while(list($h, $f) = each($handle)) {
  •         $this->file[$h] = $this->filename($f);
  •       }
  •     }
  •   }
  •   /* public: set_block(string $parent, string $handle, string $name = "")
  •    * extract the template $handle from $parent, 
  •    * place variable {$name} instead.
  •    */
  •   function set_block($parent, $handle, $name = "") {
  •     if (!$this->loadfile($parent)) {
  •       $this->halt("subst: unable to load $parent.");
  •       return false;
  •     }
  •     if ($name == "")
  •       $name = $handle;
  •     $str = $this->get_var($parent);
  •     $reg = "/<!--\s+BEGIN $handle\s+-->(.*)\n\s*<!--\s+END $handle\s+-->/sm";
  •     preg_match_all($reg, $str, $m);
  •     $str = preg_replace($reg, "{" . "$name}", $str);
  •     $this->set_var($handle, $m[1][0]);
  •     $this->set_var($parent, $str);
  •   }
  •   
  •   /* public: set_var(array $values)
  •    * values: array of variable name, value pairs.
  •    *
  •    * public: set_var(string $varname, string $value)
  •    * varname: name of a variable that is to be defined
  •    * value:   value of that variable
  •    */
  •   function set_var($varname, $value = "") {
  •     if (!is_array($varname)) {
  •       if (!emptyempty($varname))
  •         if ($this->debug) print "scalar: set *$varname* to *$value*<br>\n";
  •         $this->varkeys[$varname] = "/".$this->varname($varname)."/";
  •         $this->varvals[$varname] = $value;
  •     } else {
  •       reset($varname);
  •       while(list($k, $v) = each($varname)) {
  •         if (!emptyempty($k))
  •           if ($this->debug) print "array: set *$k* to *$v*<br>\n";
  •           $this->varkeys[$k] = "/".$this->varname($k)."/";
  •           $this->varvals[$k] = $v;
  •       }
  •     }
  •   }
  •   /* public: subst(string $handle)
  •    * handle: handle of template where variables are to be substituted.
  •    */
  •   function subst($handle) {
  •     if (!$this->loadfile($handle)) {
  •       $this->halt("subst: unable to load $handle.");
  •       return false;
  •     }
  •     $str = $this->get_var($handle);
  •     $str = @preg_replace($this->varkeys, $this->varvals, $str);
  •     return $str;
  •   }
  •   
  •   /* public: psubst(string $handle)
  •    * handle: handle of template where variables are to be substituted.
  •    */
  •   function psubst($handle) {
  •     print $this->subst($handle);
  •     
  •     return false;
  •   }
  •   /* public: parse(string $target, string $handle, boolean append)
  •    * public: parse(string $target, array  $handle, boolean append)
  •    * target: handle of variable to generate
  •    * handle: handle of template to substitute
  •    * append: append to target handle
  •    */
  •   function parse($target, $handle, $append = false) {
  •     if (!is_array($handle)) {
  •       $str = $this->subst($handle);
  •       if ($append) {
  •         $this->set_var($target, $this->get_var($target) . $str);
  •       } else {
  •         $this->set_var($target, $str);
  •       }
  •     } else {
  •       reset($handle);
  •       while(list($i, $h) = each($handle)) {
  •         $str = $this->subst($h);
  •         $this->set_var($target, $str);
  •       }
  •     }
  •     
  •     return $str;
  •   }
  •   
  •   function pparse($target, $handle, $append = false) {
  •     print $this->parse($target, $handle, $append);
  •     return false;
  •   }
  •   
  •   /* public: get_vars()
  •    */
  •   function get_vars() {
  •     reset($this->varkeys);
  •     while(list($k, $v) = each($this->varkeys)) {
  •       $result[$k] = $this->varvals[$k];
  •     }
  •     
  •     return $result;
  •   }
  •   
  •   /* public: get_var(string varname)
  •    * varname: name of variable.
  •    *
  •    * public: get_var(array varname)
  •    * varname: array of variable names
  •    */
  •   function get_var($varname) {
  •     if (!is_array($varname)) {
  •       return $this->varvals[$varname];
  •     } else {
  •       reset($varname);
  •       while(list($k, $v) = each($varname)) {
  •         $result[$k] = $this->varvals[$k];
  •       }
  •       
  •       return $result;
  •     }
  •   }
  •   
  •   /* public: get_undefined($handle)
  •    * handle: handle of a template.
  •    */
  •   function get_undefined($handle) {
  •     if (!$this->loadfile($handle)) {
  •       $this->halt("get_undefined: unable to load $handle.");
  •       return false;
  •     }
  •     
  •     preg_match_all("/\{([^}]+)\}/", $this->get_var($handle), $m);
  •     $m = $m[1];
  •     if (!is_array($m))
  •       return false;
  •     reset($m);
  •     while(list($k, $v) = each($m)) {
  •       if (!isset($this->varkeys[$v]))
  •         $result[$v] = $v;
  •     }
  •     
  •     if (count($result))
  •       return $result;
  •     else
  •       return false;
  •   }
  •   /* public: finish(string $str)
  •    * str: string to finish.
  •    */
  •   function finish($str) {
  •     switch ($this->unknowns) {
  •       case "keep":
  •       break;
  •       
  •       case "remove":
  •         $str = preg_replace('/{[^ \t\r\n}]+}/', "", $str);
  •       break;
  •       case "comment":
  •         $str = preg_replace('/{([^ \t\r\n}]+)}/', "<!-- Template $handle: Variable \\1 undefined -->", $str);
  •       break;
  •     }
  •     
  •     return $str;
  •   }
  •   /* public: p(string $varname)
  •    * varname: name of variable to print.
  •    */
  •   function p($varname) {
  •     print $this->finish($this->get_var($varname));
  •   }
  •   function get($varname) {
  •     return $this->finish($this->get_var($varname));
  •   }
  •     
  •   /***************************************************************************/
  •   /* private: filename($filename)
  •    * filename: name to be completed.
  •    */
  •   function filename($filename) {
  •     if (substr($filename, 0, 1) != "/") {
  •       $filename = $this->root."/".$filename;
  •     }
  •     
  •     if (!file_exists($filename))
  •       $this->halt("filename: file $filename does not exist.");
  •     return $filename;
  •   }
  •   
  •   /* private: varname($varname)
  •    * varname: name of a replacement variable to be protected.
  •    */
  •   function varname($varname) {
  •     return preg_quote("{".$varname."}");
  •   }
  •   /* private: loadfile(string $handle)
  •    * handle:  load file defined by handle, if it is not loaded yet.
  •    */
  •   function loadfile($handle) {
  •     if (isset($this->varkeys[$handle]) and !emptyempty($this->varvals[$handle]))
  •       return true;
  •     if (!isset($this->file[$handle])) {
  •       $this->halt("loadfile: $handle is not a valid handle.");
  •       return false;
  •     }
  •     $filename = $this->file[$handle];
  •     $str = implode("", @file($filename));
  •     if (emptyempty($str)) {
  •       $this->halt("loadfile: While loading $handle, $filename does not exist or is empty.");
  •       return false;
  •     }
  •     $this->set_var($handle, $str);
  •     
  •     return true;
  •   }
  •   /***************************************************************************/
  •   /* public: halt(string $msg)
  •    * msg:    error message to show.
  •    */
  •   function halt($msg) {
  •     $this->last_error = $msg;
  •     
  •     if ($this->halt_on_error != "no")
  •       $this->haltmsg($msg);
  •     
  •     if ($this->halt_on_error == "yes")
  •       die("<b>Halted.</b>");
  •     
  •     return false;
  •   }
  •   
  •   /* public, override: haltmsg($msg)
  •    * msg: error message to show.
  •    */
  •   function haltmsg($msg) {
  •     printf("<b>Template Error:</b> %s<br>\n", $msg);
  •   }
  • }
  •   function savetofile ($dir,$varname){
  •    $data=$this->finish($this->get_var($varname));
  •    $fp=fopen($dir,"w+");
  •    fwrite($fp,$data);
  •   }
  •    function renew(){
  •     $this->varkeys=array();
  •     $this->varvals=array();
  •     $this->file=array();
  •     }
  • ?>

  测试页面:

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  • <html>
  • <head>
  • <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  • <title>无标题文档</title>
  • </head>
  • <body>
  • <?php
  •  require("template.inc");
  •  faction staticinfo ($id){
  •   mysql_connection(localhost, root,);
  •   mysql_select_db (dbname);
  •   global $table,$template,$itpl
  •   $rs=mysql_query("select id from $table where id=$id");
  •   $array=mysql_fetch_query("$rs");
  •   $target=$array[“target”];
  •   $title=$array[“title”];
  •   $itpl=new template;
  •   
  •   //分析模板
  •   $tpl->set_file(“main”,$template);
  •   //把模板中的{title}变量换成$title
  •   $itpl->set_var(“title”,$title”);
  •   //分析整个模板
  •   $itpl->set_var(“mains”,”main”);
  •   //把mains写入文件
  •   $tpl->savetofile($target,"mains");
  •   //置空
  •   $tpl->renew();
  • ?>
  • </body>
  • </html>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-353279-1-1.html 上篇帖子: php在windows下的环境搭建 下篇帖子: php调试备份
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表