我正在尝试创建一个小模板系统,并且有一个循环遍历项目数组的函数。 目前我正在使用输出缓冲功能和包含,所以我可以加载模板文件,同时它具有该类的范围。
function loadTemplate($name, $vars) {
$buf = '';
$path = $name . '.html';
if (file_exists($path)) {
$this->vars = $vars;
ob_start();
include($path);
$buf = ob_get_clean();
}
return $buf;
}
我只是想知道我是否可以将初始模板存储在一个数组中,然后让它运行(如果它包含在内),同时保持范围,例如。
function loadTemplate($name, $vars) {
$buf = $template = '';
if (isset($this->cache[$name]))
$template = $this->cache[$name];
else {
$path = $name . '.html';
$template = file_get_contents($path);
$this->cache[$name] = $template;
}
//Exec template here with scope.
}
或者我只是在迂腐并尝试微观优化:)
答案 0 :(得分:1)
如果我是你,并且在模板文件中有复杂的操作,我会将它们保存到文件系统中。我修改了你的功能,我想你会明白那里会发生什么:
<?php
function template($name, $vars = array())
{
$cache = 'cache/'; // Path to cache folder, must be writeable
$expire = 3600 * 3; // Cache lifetime, 3 hours
$path = $name . '.html';
$cache_file = $cache . sha1($path) . '.txt'; // Generate cache file path and hash-name
// If cache file exists and it hasn't expired yet we must get cached data
if (file_exists($cache_file) && filemtime($cache_file) > (time() - $expire))
{
return unserialize(file_get_contents($cache_file));
}
// Return NULL if template file doesn't exist
if (!file_exists($path))
{
return null;
}
$this->vars = $vars;
ob_start();
include_once $path;
$output = ob_get_clean();
// Save output to the cache file
file_put_contents($cache_file, serialize($output));
return $output;
}
?>
P.S。没有测试过这个功能。
答案 1 :(得分:0)
我不认为如果再次包含模板会有很大的不同,就像你自己说的那样......它将是微优化。
但是,您可以做的是将已包含的模板源保存到数组中,并使用模板名作为数组的键。
运行loadTemplate函数时,只需执行array_key_exists
即可查看它是否已包含在内。
但如果可以,我会推荐smarty template engine。我在我的项目中使用它并发现它非常完美。我已经对它进行了一些调整以使我的代码运行更顺畅,但现在它对我来说真的很完美。
答案 2 :(得分:0)
继续包括它。唯一的选择是阅读内容然后评估它们,那将会更糟。由于页面已被解析为操作码...
,因此第二个include的开销应该明显减少答案 3 :(得分:0)
这是你可以实现的最无用的缓存。 您最好考虑HTTP条件获取实现,它根本不需要调用temlpate。然后转到操作码缓存,它将自动缓存您的包含。
但是在第一次,你必须分析你的应用程序/模板,看看你是否需要任何缓存
答案 4 :(得分:0)
将根据NullUserException的评论来查看CakePHP:)