php原生模板引擎实现
PHP原生模板引擎实现
基本模板解析
使用PHP原生语法作为模板引擎的基础,通过extract()函数将变量导入当前符号表,再通过include引入模板文件。
function render($template, $data = []) {
extract($data);
ob_start();
include $template;
return ob_get_clean();
}
变量输出与转义
在模板中直接输出变量时,应对HTML特殊字符进行转义以防止XSS攻击。
function escape($string) {
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
模板中使用示例:
<?php echo escape($user_input); ?>
控制结构支持
PHP原生语法已支持条件判断和循环结构,无需额外实现。
<?php if ($condition): ?>
<div>Content</div>
<?php endif; ?>
<?php foreach ($items as $item): ?>
<li><?php echo escape($item); ?></li>
<?php endforeach; ?>
模板继承
通过include和变量传递实现简单的模板继承机制。
基础模板(layout.php):
<!DOCTYPE html>
<html>
<head>
<title><?php echo escape($title); ?></title>
</head>
<body>
<?php include $content; ?>
</body>
</html>
子模板(page.php):
<?php
$title = "Page Title";
$content = __FILE__;
include 'layout.php';
?>
自定义模板函数
注册自定义函数到模板中,增强模板功能。
function template_function($name, $callback) {
if (!function_exists($name)) {
function _tmp_func($name, $callback) {
return function() use ($name, $callback) {
return call_user_func_array($callback, func_get_args());
};
}
$func = _tmp_func($name, $callback);
$func();
}
}
使用示例:
template_function('uppercase', function($str) {
return strtoupper($str);
});
模板中调用:
<?php echo uppercase('hello'); ?>
性能优化
通过缓存已编译的模板提高性能。
function cache_template($template, $data = []) {
$cache_file = 'cache/' . md5($template) . '.php';
if (!file_exists($cache_file) || filemtime($template) > filemtime($cache_file)) {
$content = render($template, $data);
file_put_contents($cache_file, $content);
}
return $cache_file;
}
安全注意事项
- 始终对用户输入进行转义
- 限制模板文件只能包含在特定目录
- 禁用危险的PHP函数如
eval() - 对模板文件路径进行校验,防止目录遍历攻击
function safe_include($file) {
$allowed_dir = realpath('./templates');
$path = realpath($file);
if (strpos($path, $allowed_dir) === 0) {
include $path;
} else {
throw new Exception("Invalid template path");
}
}






