php原生模板引擎实现
PHP原生模板引擎实现
基本思路
PHP本身具备模板引擎的特性,通过混合HTML和PHP代码即可实现简单的模板功能。原生实现通常基于以下核心思想:

- 使用
ob_start()和ob_get_clean()捕获输出 - 通过
extract()将变量导入当前符号表 - 利用
include或eval执行模板文件
简单实现示例
class SimpleTemplate {
protected $templateDir;
public function __construct($templateDir) {
$this->templateDir = rtrim($templateDir, '/') . '/';
}
public function render($template, $data = []) {
$path = $this->templateDir . $template;
if (!file_exists($path)) {
throw new Exception("Template not found: $path");
}
extract($data);
ob_start();
include $path;
return ob_get_clean();
}
}
使用方法
$tpl = new SimpleTemplate('templates/');
echo $tpl->render('page.php', [
'title' => 'Welcome',
'content' => 'Hello World'
]);
模板文件示例 (templates/page.php)
<!DOCTYPE html>
<html>
<head>
<title><?= htmlspecialchars($title) ?></title>
</head>
<body>
<div class="content">
<?= $content ?>
</div>
</body>
</html>
高级特性扩展
模板继承实现
public function extend($parent, $child, $data = []) {
$content = $this->render($child, $data);
$data['content'] = $content;
return $this->render($parent, $data);
}
带缓存的实现
public function renderWithCache($template, $data = [], $cacheTime = 3600) {
$cacheFile = 'cache/' . md5($template . serialize($data)) . '.php';
if (file_exists($cacheFile) &&
time() - filemtime($cacheFile) < $cacheTime) {
return file_get_contents($cacheFile);
}
$content = $this->render($template, $data);
file_put_contents($cacheFile, $content);
return $content;
}
安全注意事项
- 始终对输出进行转义:使用
htmlspecialchars()处理HTML输出 - 限制模板目录访问:确保模板文件不能直接通过URL访问
- 验证模板路径:防止目录遍历攻击
$path = realpath($this->templateDir . $template);
if (strpos($path, $this->templateDir) !== 0) {
throw new Exception("Invalid template path");
}
性能优化建议
- 避免在模板中使用复杂逻辑
- 对静态内容使用缓存
- 预编译模板为纯PHP文件
- 使用OPcache加速模板执行
这种原生实现虽然简单,但已经能满足大部分基本需求。对于更复杂的需求,可以考虑使用成熟的模板引擎如Twig或Smarty。







