我正在尝试学习一些关于PHP的东西并编写我自己的模板类.但它感觉无效.这样做会不会影响性能?如果可以的话,看一看是什么问题:
<?
class Template {
private $file, $template, $data;
public function __construct($file) {
$this->template = file_get_contents('views/wrapper.php');
$this->file = file_get_contents('views/'.$file.'.php');
}
public function __set($key, $val) { $this->data[$key] = $val; }
public function __get($key) { return $this->data[$key]; }
private function replaceAll() {
foreach($this->data AS $key => $val)
$this->template = str_replace('@'.$key, $val, $this->template);
$this->template = str_replace('{LOAD}', $this->file, $this->template);
}
public function render() {
$this->replaceAll();
echo $this->template;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我想使用一个包装器,它包含页脚+标题,其中包含侧栏/导航.所以我需要以某种方式在那里动态设置一个活动类,然后我希望能够基于构造函数或类似的东西加载视图.我正在做什么..好吗?
__get和__set函数非常慢.字符串替换也很慢.你为什么用这种方式制作模板?如果你做了更像这样的事情怎么办?
模板类
class template {
protected $templateFile;
public function __construct($template_file) {
$this->templateFile = $template_file;
}
public function render() {
require($this->templateFile);
}
}
Run Code Online (Sandbox Code Playgroud)
模板文件
<html>
<p><?= $this->someProperty ?></p>
</html>
Run Code Online (Sandbox Code Playgroud)
用法
$view = new template($template_file_path);
$view->someProperty = 'hello world';
$view->render();
Run Code Online (Sandbox Code Playgroud)
唯一的缺点是编写模板的人也可以访问编写PHP.
| 归档时间: |
|
| 查看次数: |
4397 次 |
| 最近记录: |