php原生模板引擎实现
实现原生模板引擎的基本思路
原生模板引擎的核心是将模板文件中的占位符或逻辑代码替换为实际数据或执行结果。PHP本身具备混合HTML和PHP代码的能力,但原生模板引擎可以进一步简化视图层的编写。
简单变量替换引擎
创建一个基础引擎,用于替换模板中的变量占位符:
function renderTemplate($template, $data = []) {
extract($data);
ob_start();
include $template;
return ob_get_clean();
}
使用方法:
$data = ['title' => '首页', 'content' => '欢迎光临'];
echo renderTemplate('template.php', $data);
模板文件template.php内容:
<html>
<head><title><?= $title ?></title></head>
<body>
<div><?= $content ?></div>
</body>
</html>
支持简单逻辑的引擎
扩展引擎功能,支持基本的条件判断和循环:

function render($template, $data = []) {
extract($data);
ob_start();
if (file_exists($template)) {
include $template;
}
return ob_get_clean();
}
模板示例:
<?php if ($loggedIn): ?>
<p>欢迎回来,<?= $username ?></p>
<?php else: ?>
<p>请登录</p>
<?php endif; ?>
<ul>
<?php foreach ($items as $item): ?>
<li><?= $item ?></li>
<?php endforeach; ?>
</ul>
模板继承实现
实现类似Blade的模板继承功能:
function extend($parent) {
global $__parent;
$__parent = $parent;
}
function section($name) {
global $$name;
ob_start();
}
function endsection($name) {
global $$name;
$$name = ob_get_clean();
}
function renderWithExtend($template) {
global $__parent;
ob_start();
include $template;
$content = ob_get_clean();
if ($__parent) {
extract(get_defined_vars());
ob_start();
include $__parent;
$content = ob_get_clean();
}
return $content;
}
使用示例: 子模板child.php:

<?php extend('parent.php'); ?>
<?php section('content'); ?>
<h1>子模板内容</h1>
<?php endsection('content'); ?>
父模板parent.php:
<html>
<body>
<header>网站标题</header>
<main><?= $content ?></main>
<footer>版权信息</footer>
</body>
</html>
缓存机制实现
添加简单的模板缓存功能:
function renderWithCache($template, $data = [], $cacheDir = 'cache') {
$cacheFile = $cacheDir.'/'.md5($template).'.php';
if (!file_exists($cacheDir)) {
mkdir($cacheDir, 0755, true);
}
if (!file_exists($cacheFile) || filemtime($template) > filemtime($cacheFile)) {
$content = renderTemplate($template, $data);
file_put_contents($cacheFile, $content);
}
extract($data);
include $cacheFile;
}
安全过滤处理
对输出内容进行安全过滤:
function e($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
模板中使用:
<p><?= e($userInput) ?></p>
这些方法展示了如何逐步构建一个功能完整的原生PHP模板引擎。实际应用中可以根据需求组合或扩展这些功能,创建更加强大和灵活的模板系统。






