【问题标题】:Simple template in PHP / Output buffering performancePHP中的简单模板/输出缓冲性能
【发布时间】:2017-04-27 12:11:24
【问题描述】:

我在我的脚本中使用了非常简单的模板引擎:

<?php
require_once('some_class.php');
$some_class = new some_class();

function view($file, $vars) {
    ob_start();
    extract($vars);
    include dirname(__FILE__) . '/' . $file . '.php';
    $buffer = ob_get_contents();
    ob_end_clean();
    return $buffer;
}

echo view('template', array(
    'content' => some_class::content(),
    'pages' => some_class::pages(),
    'meta_title' => some_class::$meta_title,
    'meta_description' => some_class::$meta_description
));
?>

它运行良好,但我的脚本变得更大,我正在添加新功能,有时在某些情况下加载页面需要很长时间。我的网页有时需要使用外部 API 并且有延迟。如何在没有输出缓冲的情况下重建它以工作?

【问题讨论】:

  • 您可以view() 函数中使用输出缓冲,而不是调用echo view('template', array());,只需调用函数本身。我假设您返回缓冲区,因为您有时希望将呈现的模板作为字符串,在这些情况下,您只能在此处使用输出缓冲。
  • 例如在 template.php 我有:&lt;?php echo $meta_title; ?&gt; ...我在 some_class.php 中设置了这个:&lt;?php class some_class { public static $meta_title; public static function content() { some_class::$meta_title = 'Meta title to display in template.php'; } } ?&gt;

标签: php buffer template-engine ob-start


【解决方案1】:

我认为根本没有理由使用输出缓冲。

<?php
require_once('some_class.php');
$some_class = new some_class();

function view($file, $vars) {
    extract($vars);
    include dirname(__FILE__) . '/' . $file . '.php';
}

view('template', array(
    'content' => some_class::content(),
    'pages' => some_class::pages(),
    'meta_title' => some_class::$meta_title,
    'meta_description' => some_class::$meta_description
));
?>

这做同样的事情,没有缓冲区。如果您需要将呈现的模板作为字符串(这可能只发生在代码中的 1 个位置),则只能在此处使用输出缓冲:

ob_start();
view('template', array(
    'content' => some_class::content(),
    'pages' => some_class::pages(),
    'meta_title' => some_class::$meta_title,
    'meta_description' => some_class::$meta_description
));
$buffer = ob_get_contents();
ob_end_clean();

如果您更频繁地需要将模板作为字符串,请将此逻辑包装在另一个函数中:

function render($file, $vars) {
    ob_start();
    view($file, $vars);
    $buffer = ob_get_contents();
    ob_end_clean();

    return $buffer;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 2013-11-24
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多