乙個簡單的模板類(PHP)

2021-08-27 00:22:42 字數 2717 閱讀 1485

接上話,有了乙個資料操作類,這樣專案只能簡單地運算元據,但是要達到能夠和美工一起顯示美好的頁面,則需要乙個比較好的模板引擎。與smarty這樣比較龐大的模板引擎相比,我想下面這個則真算得小得多了。

這個模板類是我以前在網上看到的,寫得比較好,所以我就引用了,還不知道作者是誰,這裡就先講一下這個類的原理。

首先,這個類只有乙個簡單的正則解析器。但是基本上可以用到了。如果再能夠在此基礎上擴充套件,我相相信這個小東西很有發展,請有相同愛好的同志們,來加入到強化他的目地。我這就拋下磚。

template.class.php

<?php

class template>';

//編譯檔案

private $template_c_file = '';

//快取檔案

private $cache_file = '';

//快取時間

public $cache_time = 0;

//內建解析器

private $preg_temp = array(

'~<\>~i'

=> '<?php echo $1; ?>', // <>

'~<\>~i'

=> '<?php echo $1[\'$2\']; ?>', // <>

'~<\>~i'

=> '<?php echo $1[\'$2\'][\'$3\']; ?>', // <>

'~<\?php\s+(include_once|require_once|include|require)\s*\(\s*(.+?)\s*\)\s*;?\s*\?>~i'

=> '<?php include \$this->_include($2); ?>', // <?php include('inc/top.php'); ?>

'~<\>~' => '<?php echo $1; ?>', // <>

'~<\>~' => '<?php $1; ?>', // <>

'~<\?=\s*~' => '<?php echo ', // <?=

); /**

*構造器

*/public function __construct() }

/***變數賦值

*@param $key mixed 鍵名

*@param $value mixed 值

*/public function assign($key , $value = '')

else }

/***顯示頁面

*@param $file string 模板檔名

*/public function display($file)

/***返回快取區內容

*@param $file string 模板檔名

*@return $content string 快取內容

*/public function fetch($file)

//以下獲取快取區的內容

ob_start();

@extract($this->vars , extr_overwrite);

include ($this->template_c_dir . $this->template_c_file);

$content = ob_get_contents();

ob_end_clean();

//$this->store_buff($content);

return $content; }

/* *替換分隔符,以及替換解析器的內容

*@param $content string 讀取的內容

*@return $token_content string 替換後的內容

*/public function token($content)>' , $token_content);

} $token_content = preg_replace(array_keys($this->preg_temp), $this->preg_temp , $token_content);

return $token_content; }

/* *生成儲存

*@param $content string 讀取的內容

* public function store_buff($content)

*/ /* *編譯儲存

*@param $content string 讀取的內容

* */

public function complie($content)

/**讀取檔案的內容

*@param $file string 檔名

*@return $content string 檔案內容

*/public function readfile($file)

fclose($fp);

unset($fp);

return $content;

} else }

/* *模板巢狀

*@param $file string 檔名

*@return string 檔案的絕對位址

*/public function _include($file)

else }}

?>

有了這個模板,你可以忘記那些大型的模板,畢竟你的美工不會在他的切片檔案裡寫那麼多smarty的標記,而只要他切好,你可以直接用,不用去修改images , css ,js 位址了。

乙個簡單的模板類(PHP)

有了乙個資料操作類,這樣專案只能簡單地運算元據,但是要達到能夠和美工一起顯示美好的頁面,則需要乙個比較好的模板引擎。與smarty這樣比較龐大的模板引擎相比,我想下面這個則真算得小得多了。這個模板類是我以前在網上看到的,寫得比較好,所以我就引用了,還不知道作者是誰,這裡就先講一下這個類的原理。首先,...

乙個簡單的類模板的使用

include include using namespace std template class mylist void print private t a t b template 不可少 void mylist print 宣告和定義都要放在同乙個 檔案中,否則會出現錯誤提示 error l...

乙個簡單的資料池模板類

前不久,因為專案的要求對資料訪問十分頻繁,如果每次都是分配記憶體,然後釋放,會產生大量的記憶體碎片,所以設計了乙個資料池模板類,該類很簡單,主要功能有 1 初始化資料池 2 清空資料池 3 取得一段資料緩衝區 4 釋放一段資料緩衝區 5 取得緩衝區記錄數 如何使用 使用步驟如下 1,建立資料池 cd...