毛毛蟲教你寫乙個屬於自己的模板引擎

2021-12-29 20:18:14 字數 2642 閱讀 7014

#phpchina首發#

smarty一直被人視為是多餘的東西,我覺得認為smarty多餘的人才是多餘的....不說這些了。今天我就教大家寫個模板引擎,讓大家都可以寫乙個屬於自己的模板引擎,而且看完這篇文章之後,你對smarty的認識會更進一步的。我的模板引擎名叫stupid("傻瓜"的意思),我不喜歡太聰明的東西!

stupid模板引擎是由3個檔案組成,他們分別是:stupid.class.php,stupid_parser.class.php,stupid_debugger.class.php。

stupid.class.php的任務是設定變數,模板路徑,和顯示等功能,而stupid_parser.class.php就是編譯模板檔案的,stupid_debugger.class.php是用來除錯用的。

好了,我們現在就先編寫stupid.class.php吧。

1.新建乙個php檔名為:stupid.class.php。

我們的類叫stupid,我們先設計一下成員變數吧。

成員變數有:$_tpl_vars, $_tpl_file, $_parser, $_debugger;

$_tpl_vars: 用來儲存模板變數的;

$_tpl_file: 用來儲存模板檔名的;

$_parser: 儲存stupidparser物件的,就是編譯物件;

$_debugger: 儲存stupiddebug物件的,就是除錯物件;

下面定義了兩個常量,用來存放模板資料夾和編譯資料夾的:

define(tpl_dir, ./templates/);

define(tpl_c_dir, ./templates_c/);

開始編碼》

<?php

define(tpl_dir, ./templates/);

define(tpl_c_dir, ./templates_c/);

class stupid

?>

開始寫個構造器》

public function stupid()

}在構造器中,我們判斷了模板路徑和編譯路徑是否設定正確.

設計我們的方法

我們這個類中主要有以下方法:

assign(), set_tpl_dir(), set_parsed_dir(), display(), debug().

assign()方法:

assign()的用處是設定模板變數.**如》

public function assign($var, $value) else

}我們先判斷使用者是否設定了變數名,用isset($var) && trim($var) != 來判斷, trim($var) != 是防止使用者以空格來設定變數名.如果設定變數正確,我們就將他儲存到成員變數_tpl_vars中.

display()方法

display()方法是stupid類中最重要的方法,他是用來顯示和檢測模板是否更新了,更新了就再編譯,沒有更新就用原來編譯之後的檔案.

**如》

public function display($tpl_file)

$parsed_file = tpl_c_dir.md5($tpl_file)..php;

if(!file_exists($parsed_file) || filemtime($parsed_file) < filemtime($template_file))

include $parsed_file;

}這個方法是根據!file_exists($parsed_file)||filemtime($parsed_file)< filemtime($template_file)這條語句來判斷是否編譯過和模板檔案是否更新過, 沒有編譯過和更新過模板檔案都要重新編譯.我們就要引入stupid_parser.class.php,並建立stupidparser物件,對模板檔案進行編譯.編譯完,我們就引入編譯之後的檔案.這個編譯之後的模板檔案就是乙個普通的php檔案.

debug()方法

debugg()方法就比較簡單,就是引入stupid_debugger.class.php檔案,建立stupiddebuger物件,呼叫stupiddebuger的start方法進行除錯.

**如》

public function debug ($tpl_file) else

}至此,我們的stupid類就寫完了!下次我要介紹stupidparser類的編寫.請繼續支援.大家有什麼意見或者建議可以提出!

show show全相:

<?php

define(tpl_dir, ./templates/);

define(tpl_c_dir, ./templates_c/);

class stupid

}public function assign($var, $value) else

}public function display($tpl_file)

$parsed_file = tpl_c_dir.md5($tpl_file)..php;

if(!file_exists($parsed_file) || filemtime($parsed_file) < filemtime($template_file))

include $parsed_file;

}function debug($tpl_file) else }}

?>

乙個自己寫的PHP模板引擎

這是乙個自己寫的編譯型的模板引擎 不包括快取部分 貼上 有問題可以隨時跟帖。單檔案版 jtemplate.class.php templatedir templatedir this templatecompiledir templatecompliedir 顯示模板方法 param string ...

用Django寫乙個屬於自己的部落格站點

用django寫乙個屬於自己的部落格站點 首先,先寫好html靜態檔案和css等相關檔案 這邊是用atom開發 1.要裝有python3.x 3.寫好html靜態檔案和css 1.建立乙個新的空資料夾 2.開啟終端 開始鍵 r 開啟 執行 輸入cmd cd到該資料夾,建立乙個firstsite的dj...

建立乙個屬於自己的shell

1 寫乙個屬於自己的微型myshell 2 功能 myshell ls 3 能夠執行基礎linux 命令 4 5 6 include7 include8 include9 include10 include11 1 獲取終端輸入 12 2 解析輸入 按空格解析到乙個乙個的命令引數 13 3 建立乙個...