標籤:
1,設定檔:config.php
<?php
/**
*@yzt
*TPL_CACHE 用於指定產生.php 的路徑(檔案)
*TPL_PATH 用於指定產生 模板的檔案路徑
**/
define(‘TPL_CACHE‘,‘./cache/‘);
define(‘TPL_PATH‘,‘./views/‘);
2,測試 demo1.php
/**
*include 檔案匯入
*compact 資料數組化
***/
<?php
include ‘config.php‘;
include ‘tpl.func.php‘;
$title = ‘看到女神容易自悲‘;
$content = ‘要想辦法拉平你們的關係,不然下手准失敗‘;
$footercontent = ‘因為你會扭捏,不自然,女神就會跟你打低分‘;
$data = [
‘yzt‘ => ‘yzt‘,
‘xyy‘ => ‘xyy‘,
];
display(‘moban.html‘,compact(‘title‘,‘content‘,‘data‘,‘footercontent‘));
3,引擎(核心)tpl.func.php
<?php
//兩個參數 1,html 模板; 2,需要修改的參數
function display($tplFile, $tplVars = null)
{
$tplFilePath = rtrim(TPL_PATH,‘/‘) . ‘/‘ . $tplFile;
if (!file_exists($tplFilePath)) {
exit(‘模版檔案不存在‘);
}
$html = compile($tplFilePath);
$cacheFileName = parsePath($tplFile);
if (!check_cache_dir(TPL_CACHE)) {
exit(‘緩衝目錄不可寫‘);
}
if (!file_put_contents($cacheFileName, $html)) {
exit(‘快取檔案寫入失敗‘);
}
if (is_array($tplVars)) {
extract($tplVars);
include $cacheFileName;
}
}
function check_cache_dir($path)
{
if(!file_exists($path) || !is_dir($path)) {
return mkdir($path,0755,true);
}
if(!is_writeable($path) || !is_readable($path)) {
return chmod($path,0755);
}
return true;
}
function parsePath($tplFile)
{
$path = rtrim(TPL_CACHE,‘/‘).‘/‘.str_replace(‘.‘,‘_‘,$tplFile).‘.php‘;
return $path;
}
function compile($path)
{
$keys = [
‘{if %%}‘ => ‘<?php if(\1): ?>‘,
‘{else}‘ => ‘<?php else : ?>‘,
‘{else if %%}‘ => ‘<?php elseif(\1) : ?>‘,
‘{elseif %%}‘ => ‘<?php elseif(\1) : ?>‘,
‘{/if}‘ => ‘<?php endif;?>‘,
‘{$%%}‘ => ‘<?=$\1;?>‘,
‘{foreach %%} ‘ => ‘<?php foreach(\1) :?>‘,
‘{/foreach}‘ => ‘<?php endforeach;?>‘,
‘{for %%}‘ => ‘<?php for(\1):?>‘,
‘{/for}‘ => ‘<?php endfor;?>‘,
‘{while %%}‘ => ‘<?php while(\1):?>‘,
‘{/while}‘ => ‘<?php endwhile;?>‘,
‘{continue}‘ => ‘<?php continue;?>‘,
‘{break}‘ => ‘<?php break;?>‘,
‘{$%% = $%%} => ‘<?php $\1 = $\2;?>‘,
‘{$%%++}‘ => ‘<?php $\1++;?>‘,
‘{$%%--}‘ => ‘<?php $\1--;?>‘,
‘{comment}‘ => ‘<?php /* ‘,
‘{/comment}‘ => ‘ */ ?>‘,
‘{/*}‘ => ‘<?php /* ‘,
‘{*/}‘ => ‘* ?>‘,
‘{section}‘ => ‘<?php ‘,
‘{/section}‘ => ‘?>‘,
‘{include %%}‘ => ‘<?php include \1;?>‘,
];
$file = file_get_contents($path);
foreach ($keys as $key => $val) {
$pattern = ‘#‘. str_replace(‘%%‘, ‘(.+)‘, preg_quote($key,‘#‘)) .‘#imsU‘;
$replace = $val;
if (stripos($pattern,‘include‘)) {
$file = preg_replace_callback($pattern, ‘parseInclude‘, $file);
} else{
$file = preg_replace($pattern, $replace, $file);
}
}
return $file;
}
function parseInclude($data)
{
$path = str_replace(array(‘\‘‘,‘"‘),‘‘,$data[1]);
//data[1]就是-------footer.html
$cacheFileName = parsePath($path);
display($path);
return ‘<?php include "‘.$cacheFileName.‘";?>‘;
}
4,模板 moban.html
<html>
<head>
<title>{$title}</title>
</head>
<body>
{$content}
<br />
{foreach $data as $key => $value}
{$key} ------{$value} <br />
{/foreach}
<hr />
<h1>這是這是是這是指令碼</h1>
{include footer.html}
</body>
</html>
php基本的模板引擎