Just for fun——PHP框架之简单的模板引擎 原理

原理

使用模板引擎的好处是数据和视图分离。一个简单的PHP模板引擎原理是

  1. extract数组($data),使key对应的变量可以在此作用域起效
  2. 打开输出控制缓冲(ob_start)
  3. include模板文件,include遇到html的内容会输出,但是因为打开了缓冲,内容输出到了缓冲中
  4. ob_get_contents()读取缓冲中内容,然后关闭缓冲ob_end_clean()

实现

封装一个Template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
复制代码<?php

class Template {
private $templatePath;
private $data;

public function setTemplatePath($path) {
$this->templatePath = $path;
}

/**
* 设置模板变量
* @param $key string | array
* @param $value
*/
public function assign($key, $value) {
if(is_array($key)) {
$this->data = array_merge($this->data, $key);
} elseif(is_string($key)) {
$this->data[$key] = $value;
}
}


/**
* 渲染模板
* @param $template
* @return string
*/
public function display($template) {
extract($this->data);
ob_start();
include ($this->templatePath . $template);
$res = ob_get_contents();
ob_end_clean();
return $res;
}

}

测试

test.php

1
2
3
4
5
6
7
8
9
10
11
复制代码<?php

include_once './template.php';

$template = new Template();
$template->setTemplatePath(__DIR__ . '/template/');
$template->assign('name', 'salamander');
$res = $template->display('index.html');


echo $res;

template目录下index.html文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
复制代码<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板测试</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
h1 {
text-align: center;
padding-top: 20px;
}
</style>
</head>
<body>
<h1><?=$name?></h1>
</body>
</html>

Tip

为什么display要返回一个字符串呢?原因是为了更好的控制,嵌入到控制器类中。
对于循环语句怎么办呢?这个的话,请看流程控制的替代语法

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%