duanping1920 2017-04-27 12:11
浏览 45
已采纳

PHP /输出缓冲性能的简单模板

I'm using in my script very simple template engine:

<?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
));
?>

It worked well but my script grows bigger and i'm adding new functions and sometimes in some situations it take a lot time to load page. My webpage need to use external API sometime and there are delays. How can i rebuild this to work without output buffering?

  • 写回答

1条回答 默认 最新

  • du512053619 2017-04-28 13:45
    关注

    I see no reason to use output buffering at all.

    <?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
    ));
    ?>
    

    This does the same thing, without the buffer. If you need the rendered template as a string (which probably only happens in 1 place in your code), you can use output buffering only there:

    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();
    

    If you need templates as a string more often, wrap this logic in another function:

    function render($file, $vars) {
        ob_start();
        view($file, $vars);
        $buffer = ob_get_contents();
        ob_end_clean();
    
        return $buffer;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题