自定義min版smarty模板引擎MinSmarty.class.php文件及用法

字號:


    本文實例講述了自定義的min版smarty模板引擎MinSmarty.class.php文件。分享給大家供大家參考,具體如下:
    一、smarty的優(yōu)點
    smarty是一個使用PHP寫出來的模板引擎,是目前業(yè)界最著名的PHP模板引擎之一。它分離了邏輯代碼和外在的內容,提供了一種易于管理和使用的方法,用來將原本與HTML代碼混雜在一起PHP代碼邏輯分離。簡單的講,目的就是要使PHP程序員同前端人員分離,使程序員改變程序的邏輯內容不會影響到前端人員的頁面設計,前端人員重新修改頁面不會影響到程序的程序邏輯,這在多人合作的項目中顯的尤為重要。
    二、寫一個簡單的smarty模版類
    具體代碼如下:
    <?php
     class MinSmarty{
     // 模版文件的路徑
     var $template_dir = "./templates/";
     // 模版文件被替換后的文件 命名格式為com_對應的tpl.php
     var $complie_dir = "./templates_c/";
     // 存放變量值
     var $tpl_vars = array();
     // 這里使用兩個方法實現(xiàn)assign 和 display
     function assign($tpl_var,$var=NULL){
      if($tpl_var!=NULL){
      $this->tpl_vars[$tpl_var]=$var;
      }
     }
     // 這里編寫display方法的實現(xiàn)
     function display($tpl_file){
      // 讀取這個模版文件->替換可以運行的php文件(編譯后文件)
      $tpl_file_path=$this->template_dir.$tpl_file;  // 模版文件的路徑
      $complie_file_path=$this->complie_dir."com_".$tpl_file.".php";  //編譯后的文件路徑
      // 判斷文件是否存在
      if(!file_exists($tpl_file_path)){
      return false;
      }
      // 不讓每次執(zhí)行都生成編譯文件
      if(!file_exists($complie_file_path) || filemtime($tpl_file_path)>filemtime($complie_file_path)){
      $fp1_file_con=file_get_contents($tpl_file_path); // 獲取模版文件的全部內容
      // 這里進行正則替換把  模版文件中的代碼 {$title} 替換成 <?php echo $this->tpl_vars['title'];? >
      $pattern=array(
         '/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i'
      );
      $replace=array(
         '<?php echo $this->tpl_vars["${1}"];?>'
      );
      $new_str=preg_replace($pattern,$replace,$fp1_file_con);  // 替換后的內容
      file_put_contents($complie_file_path,$new_str);  // 替換后的內容生成一個php文件
      }
      // 引入編譯后的文件
      include_once("$complie_file_path");
     }
     }
    ?>
    下面的代碼是對該類的測試
    intro.php代碼如下:
    <?php
      include_once("MySmarty.class.php");
      $title="這里是標題";
      $content="這里是內容111111";
      $MySmarty=new MySmarty();
      $MySmarty->assign("title",$title);
      $MySmarty->assign("content",$content);
      $MySmarty->display("intro.tpl");
    ?>
    模版如下:
    intro.tpl:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>{$title}</title>
    </head>
    <body>
    {$content}
    </body>
    </html>
    希望本文所述對大家基于smarty模板的PHP程序設計有所幫助。