phpテンプレート関数正規実装コード

2736 ワード

phpcms、discuzのソースコードを見たことがあるので、革新に欠けているかもしれませんが、原理はほとんど通じていますが、細部の処理は少し異なるかもしれません.
本題を話して、次に具体的な実現過程について話します.
1.まずテンプレートファイルをどこに置くかを考えてみましょう.変換後のphpファイルはどこに置きますか?どうやって命名しますか?直接ソース:
 
  
function template($tpl = 'index',$dir = 'hello')
{
if(!file_exists($pd = TPL_PATH.$dir.'/'))@mkdir($pd,0777) or die("$pd ");// cache/tpl/hello/
if(!file_exists($td = TPL.$dir.'/'))@mkdir($td,0777) or die("$td ");// data/tpl/hello/

$t2p = $pd.$tpl.'.php';// php , cache/tpl/hello/index.php
$t2h = $td.$tpl.'.html';//html , data/tpl/hello/index.html

2.正則変換はいつ必要ですか.正規後のphpファイルが存在しない場合や、正規前のhtmlファイルが変更された場合でもよい.ここではfilemtime(string$path)関数を使用し、ファイルの最近の変更時間を返します.
 
  
if(!file_exists($t2p) || @filemtime($t2p) < @filemtime($t2h) )// , php
{
template_go($t2p,$t2h);//
}
return $t2p;// php , : include template('header','hello');
}

3.テンプレート変換を開始し、htmlファイルから読み出し、正規に置き換え、phpファイルに書き込む.
 
  
function template_go($t2p,$t2h)
{
$str = @file_get_contents($t2h);//
if($str === false) exit(" , !");
$str = template_do($str);//
@chmod($t2p,0777);
return $str = file_put_contents($t2p, $str);//
}

4.正規規則、いくつかの比較的簡略な正規置換文法.
 
  
function template_do($str)
{
$str = preg_replace('/([
\r+])\t+/s', '\\1', $str);// TAB 。 /s
$str = preg_replace('/\{\$(.*)\}/Us', '', $str);/*{$xx} , /U, 。 */
$str = preg_replace('/\{php (.+)\}/', '', $str);/*{php xxxx} , /s, */
$str = preg_replace('/\{template(.*)\}/Us', '', $str);
/*{template(xx,yy)} */
$str = preg_replace('/\{include (.*)\}/Us', '', $str);/*{include xx.php} */
$str = "".$str;
//$str = preg_replace('/\s+/', ' ', $str);//
return $str;
}

もちろん、この関数は今でも粗末で、改善されることを期待しています.
ps:これは私が初めてブログを書いたのですが、暇があれば技術ブログを書いて、心得を話して、経験と教訓を総括して、牛たちに勉強したいと思っていました.
また、ブログは保存しやすいので、手間が省けます.ほほほ.