php模板引擎实现
实现PHP模板引擎的基本思路
PHP模板引擎的核心目标是将业务逻辑与视图分离,通过占位符或特定语法将动态数据嵌入静态模板。以下是几种常见实现方式:
原生PHP作为模板引擎
直接使用PHP原生语法作为模板是最简单的方式:
<html>
<body>
<h1><?php echo htmlspecialchars($title); ?></h1>
<ul>
<?php foreach ($items as $item): ?>
<li><?php echo $item; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
自定义简单模板引擎
创建一个基础模板引擎类,通过文件读取和字符串替换实现:
class SimpleTemplateEngine {
private $templateDir;
public function __construct($templateDir) {
$this->templateDir = rtrim($templateDir, '/').'/';
}
public function render($template, array $data = []) {
$templatePath = $this->templateDir . $template;
if (!file_exists($templatePath)) {
throw new Exception("Template $template not found");
}
extract($data, EXTR_SKIP);
ob_start();
include $templatePath;
return ob_get_clean();
}
}
使用正则表达式实现模板标签
通过正则表达式替换自定义模板语法:
class RegexTemplateEngine {
public function render($template, $data) {
$content = file_get_contents($template);
// 替换变量 {{var}}
$content = preg_replace_callback('/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/',
function($matches) use ($data) {
return $data[$matches[1]] ?? '';
}, $content);
// 替换循环 {% for item in items %}...{% endfor %}
$content = preg_replace_callback(
'/\{%\s*for\s+(\w+)\s+in\s+(\w+)\s*%\}(.*?)\{%\s*endfor\s*%\}/s',
function($matches) use ($data) {
$items = $data[$matches[2]] ?? [];
$result = '';
foreach ($items as $item) {
$result .= str_replace($matches[1], $item, $matches[3]);
}
return $result;
}, $content);
return $content;
}
}
编译型模板引擎实现
更高级的实现可以将模板编译为PHP代码再执行:
class CompiledTemplateEngine {
private $cacheDir;
public function __construct($cacheDir) {
$this->cacheDir = $cacheDir;
}
public function compile($template) {
$code = file_get_contents($template);
// 转换模板语法为PHP代码
$code = preg_replace('/\{\{\s*(.+?)\s*\}\}/', '<?php echo $1; ?>', $code);
$code = preg_replace('/\{%\s*if\s+(.+?)\s*%\}/', '<?php if($1): ?>', $code);
$code = preg_replace('/\{%\s*endif\s*%\}/', '<?php endif; ?>', $code);
$cacheFile = $this->cacheDir.'/'.md5($template).'.php';
file_put_contents($cacheFile, $code);
return $cacheFile;
}
public function render($template, $data) {
$cacheFile = $this->compile($template);
extract($data);
ob_start();
include $cacheFile;
return ob_get_clean();
}
}
使用现有模板引擎
PHP生态系统中有多个成熟的模板引擎可供选择:
-
Twig:
require_once 'vendor/autoload.php'; $loader = new \Twig\Loader\FilesystemLoader('templates'); $twig = new \Twig\Environment($loader); echo $twig->render('index.html', ['name' => 'World']); -
Blade (Laravel的模板引擎):
$compiler = new \Illuminate\View\Compilers\BladeCompiler; $engine = new \Illuminate\View\Engines\CompilerEngine($compiler); $finder = new \Illuminate\View\FileViewFinder(['path/to/views']); $factory = new \Illuminate\View\Factory($engine, $finder); echo $factory->make('view')->with('data', $value); -
Smarty:
require_once 'smarty/libs/Smarty.class.php'; $smarty = new Smarty; $smarty->assign('name', 'World'); $smarty->display('index.tpl');
模板引擎的关键特性
- 变量输出:安全地输出变量,自动转义HTML
- 控制结构:支持条件判断、循环等逻辑
- 模板继承:通过布局模板和区块实现DRY原则
- 过滤器:对输出内容进行格式化处理
- 缓存机制:提升重复渲染的性能
实现模板引擎时需要考虑安全性问题,特别是对用户输入的自动转义,防止XSS攻击。成熟的模板引擎如Twig已经内置了安全防护机制。







