框架中的模板引擎 模板类
<?php
class Tpl
{
protected $viewDir = './view/';
protected $cacheDir = './cache/';
protected $lifeTime = 3600;
protected $vars = [];
public function __construct($viewDir = null, $cacheDir = null, $lifeTime = null)
{
if(!empty($viewDir)){
if($this->checkDir($viewDir)){
$this->viewDir = $viewDir;
}
}
if(!empty($cacheDir)){
if($this->checkDir($cacheDir)){
$this->cacheDir = $cacheDir;
}
}
if(!empty($lifeTime)){
$this->lifeTime = $lifeTime;
}
}
protected function checkDir($dirPath)
{
if(!file_exists($dirPath) || !is_dir($dirPath)){
return mkdir($dirPath, 0755, true);
}
if(!is_writeable($dirPath) || !is_readable($dirPath)){
return chmod($dirPath, 0755);
}
return true;
}
public function assign($name, $value)
{
$this->vars[$name] = $value;
}
public function display($viewName, $isInclude = true, $uri = null)
{
$viewPath = rtrim($this->viewDir, '/').'/'.$viewName;
if(!file_exists($viewPath)){
die('模板文件不存在');
}
$cacheName = md5($viewName.$uri).'.php';
$cachePath = rtrim($this->cacheDir,'/').'/'.$cacheName;
if(!file_exists($cachePath)){
$php = $this->compile($viewPath);
file_put_contents($cachePath, $php);
}else{
$isTimeout = (filectime($cachePath) + $this->lifeTime) > time() ? false:true;
$isChange = filemtime($viewPath) > filemtime($cachePath)?true:false;
if($isTimeout || $isChange){
$php = $this->compile($viewPath);
file_put_contents($cachePath, $php);
}
if($isInclude){
extract($this->vars);
include $cachePath;
}
}
}
protected function compile($filePath)
{
$html = file_get_contents($filePath);
$array = [
'{$%%}' => '<?=$\1; ?>',
'{foreach %%}' => '<?php foreach (\1): ?>',
'{/foreach}' => '<?php endforeach?>',
'{include %%}' => '',
'{if %%}' => '<?php if (\1): ?>',
];
foreach ($array as $key => $value) {
$pattern = '#' . str_replace('%%', '(.+?)', preg_quote($key, '#')) . '#';
if(strstr($pattern, 'include')){
$html = preg_replace_callback($pattern, [$this,'parseInclude'], $html);
}else{
$html = preg_replace($pattern, $value, $html);
}
}
return $html;
}
protected function parseInclude($data)
{
$fileName = trim($data[1], '\'"');
$this->display($fileName, false);
$cacheName = md5($fileName).'.php';
$cachePath = rtrim($this->cacheDir,'/').'/'.$cacheName;
return '<?php include "'.$cachePath.'"?>';
}
}
test.php
<?php
include 'Tpl.php';
$tpl = new TpL();
$title = 'hello';
$data = ['aaa', 'bbb'];
$head = '头部';
$tpl->assign('title', $title);
$tpl->assign('data', $data);
$tpl->assign('head', $head);
$tpl->display('test.html');
./view/test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{$title}</title>
</head>
<body>
{include head.html}
{foreach $data as $value}
{$value}<br/>
{/foreach}
</body>
</html>
./view/head.html
<div>{$head}</div>
|