2012-02-20 39 views
0

我将我的模板存储为文件,并希望有机会将它们存储在MySql数据库中。从数据库/字符串获取模板

我的模板系统

//function of Template class, where $file is a path to a file 
function fetch() { 
    ob_start(); 
    if (is_array($this->vars)) extract($this->vars); 
    include($file); 
    $contents = ob_get_contents(); 
    ob_end_clean(); 
    return $contents; 
} 

function set($name, $value) { 
    $this->vars[$name] = is_object($value) ? $value->fetch() : $value; 
} 

用法:

$tpl = & new Template('path/to/template'); 
$tpl->set('titel', $titel); 

模板例如:

<h1><?=titel?></h1> 
<p>Lorem ipsum...</p> 

我的方法

  1. 从数据库中选择模板作为一个String
  2. 我得到的是像$第三方物流=“< H1> <?= $ Titel的? > ...“
  3. 现在我想将它传递给模板系统,所以我伸出我的构造函数和取功能:

函数取(){

if (is_array($this->vars)) extract($this->vars); 
ob_start(); 
if(is_file($file)){ 
    include($file); 
}else{ 
     //first idea: eval ($file); 
    //second idea: print $file; 
} 
$contents = ob_get_contents(); 
ob_end_clean(); 
return $contents; 
} 

” eval'给了我一个解析异常,因为它把整个字符串解释为php,而不仅仅是php部分。'print'真的很奇怪:它不打印介于两者之间的工作人员,但我可以在源代码中看到它该页面.php功能被忽略了。

那我该怎么试试呢?

回答

1

也许不是最好的解决办法,但它的简单,它应该工作:

  1. 从数据库中提取模板
  2. 写一个文件与模板
  3. 包含这个文件
  4. (可选:删除文件)

如果向模板表添加Timestamp列,则可以使用该文件系统作为缓存。只需比较文件和数据库的时间戳,以确定是否足以重新使用该文件。

+0

是的,我可能会与该走了,我想过这个问题之前:) – 2012-02-27 17:51:02

1

如果您将'?>'添加到您的评估中,它应该可以正常工作。

<?php 
$string = 'hello <?php echo $variable; ?>'; 
$variable = "world"; 
eval('?>' . $string); 

但是你应该知道eval()是一个相当缓慢的事情。其产生的操作码无法在APC(或类似的)中缓存。您应该找到一种方法将模板缓存在磁盘上。对于你而言,每次需要时你都不需要从数据库中提取它们。你可以使用常规的操作码缓存(由APC透明地完成)。每当我看到一些半成品的本土“模板引擎”时,我会问自己,为什么作者不依赖现有模板引擎中的一个?他们中的大多数已经解决了你可能有的大多数问题。 Smarty(和Twig,phpTAL,...)使它成为一个真正的魅力,可以从任何你喜欢的地方抽取模板源(同时试图保持最佳性能)。你有什么特别的理由不使用其中之一?

+0

+1对“为什么另起炉灶?” – 2012-02-27 14:06:07

+0

因为我现有的模板系统 - 基于文件,是1类,大约30行,我可以在我的模板文件中使用本机php。 - 我想要和需要的。 数据库功能只是一个实验,用于了解有关php的更多信息,甚至可能不会被使用。 – 2012-02-27 17:50:03

1

我会做几乎相同的事情,除了我宁愿取决于本地文件时间戳,而不是数据库。

就像这样:每个文件的TTL(过期时间)可以说60秒。真正的原因是为了避免数据库太难/经常不必要地访问数据库,您将很快意识到文件系统访问比网络和mysql更快,特别是如果mysql实例在远程服务器上运行。

# implement a function that gets the contents of the file (key here is the filename) 
# from DB and saves them to disk. 
function fectchFreshCopy($filename) { 
    # mysql_connect(); ... 
} 


if (is_array($this->vars)) extract($this->vars); 
ob_start(); 
# first check if the file exists already 
if(file_exits($file)) { 
    # now check the timestamp of the files creation to know if it has expired: 
    $mod_timestamp = filemtime($file); 
    if ((time() - $mod_timestamp) >= 60) { 
     # then the file has expired, lets fetch a fresh copy from DB 
     # and save it to disk.. 
     fetchFreshCopy(); 
    } 
}else{ 
    # the file doesnt exist at all, fetch and save it! 
    fetchFreshCopy(); 
} 

include($file); 
$contents = ob_get_contents(); 
ob_end_clean(); 
return $contents; 
} 

干杯,希望这就是有用

+0

好吧,使用时间戳可能对缓存有好处,但如果模板本身没有经常更改,就不够好。任何建议像一个哈希?或者,我应该只用“我已更改,请获取新的本地副本并将其设置为false” - 标志? {我认为创建和写入文件也是'昂贵的'} – 2012-02-27 20:27:08

相关问题