便宜的php模板与vprintf?

时间:2009-05-08 08:41:39

标签: php function templates templating

确定, 所以printf / sprint / vprintf都接受某种类型说明符语法%[num] [type]。 (http://us2.php.net/sprintf参见示例3和4)其中num是该类型的索引。

实施例: vprintf('Number%1 $ d string%2 $ s。String%2 $ s,number%1 $ d',array(1,“no”));

是的,它是有限的......你需要维护索引。但它本地语言和(我认为)快速。

我只是想了解一下这对于第二阶段是多么有用:http://www.techfounder.net/2008/11/18/oo-php-templating/

(如果有人知道printf / vprintf的速度,那将不胜感激)

我正在谈论的完整例子:

frontpage.php:

  

<html>

     

<head>

     

<title> %1$s </title>

     

</head>

     

<body>

     

Hello %2$s! You have reached page: %1$s!

     

</body>

     

</html>

whatever.php:

  

ob_start();

     

include frontpage.php;

     

$ob_output = ob_get_clean();

     

vprintf($ob_output,"Page Title","Bob");

3 个答案:

答案 0 :(得分:6)

如果您想要便宜的PHP模板,请使用带有PHP表达式块的单独文件。可以使用printf样式的格式字符串来创建模板系统,但是我可以通过这种方法看到两个主要问题:速度和可读性。 printf函数适用于较短的字符串,虽然我手头没有任何统计信息,但我认为可以安全地在一个字符串上运行sprintf()vprintf()表示页面主体的巨大字符串将比在文件中使用PHP表达式块慢。

这引出了下一个问题:可读性。比较这两个HTML模板:

<html>
<head>
   <title>%s</title>
</head>
<body>
<div id="main">
    <h1>%s</h1>
    <p>%s</p>
</div>
<div id="other">
    <p>%s</p>
</div>
<p id="footer">
    %s. Took %.2f seconds to generate.
</p>
</body>
</html>

<html>
<head>
   <title><?= $title ?></title>
</head>
<body>
<div id="main">
    <h1><?= $header ?></h1>
    <p><?= $body_text ?></p>
</div>
<div id="other">
    <p><?= $misc_info ?></p>
</div>
<p id="footer">
    <?= $copyright ?>. Took <?= $load_time ?> seconds to generate.
</p>
</body>
</html>

或者,假设我已经决定使用带索引参数的格式字符串。说,像这样:

<h1>%1$s</h1>
<p>%2$s</p>
<span id="blah">%3$s</p>
<p>%4$s</p>
<p>%5$s</p>

现在,如果我想切换订单怎么办?

<h1>%1$s</h1>
<p>%3$s</p>
<span id="blah">%5$s</p>
<p>%4$s</p>
<p>%2$s</p>

这些显然是人为的,但想想从长远来看如何维护printf模板。

因此,通常,如果您想要快速而简单的PHP模板,请使用包含PHP表达式块的模板文件。 printf函数在处理较小的字符串格式化任务方面要好得多。

答案 1 :(得分:3)

我通常有两个文件:

  • 某种控制器(recipes.controller.php重写为/ recipes / 123)
  • 控制器的许多视图之一(recipes.view.html)

我只是在控制器中完成所有逻辑/数据库工作,然后在最后包含适当的视图。该视图可以访问控制器中的所有变量,因此我已经创建了诸如$ title,$ ingredients []等的东西。我不确定为什么人们会让它变得更复杂。这很容易理解。

视图文件基本上看起来像这样:

<html>
<head>
<title><?=$title ?></title>
</head>
etc...

答案 2 :(得分:1)

PHP的创建者Rasmus Lerdorf更愿意将他的变量包括在内:

    <select class="f" name="cat" id="f_cat" size="1">
      <option selected>Category</option>
<?php foreach($categories as $cat) echo <<<EOB
      <option value="{$cat}">{$cat}</option>

EOB;
?>

作为参考,<<<EOBEOB;heredoc

来源:Rasmus Lerdorf的The no-framework PHP MVC Framework