insanebear insanebear - 4 months ago 22
PHP Question

Simple template in PHP / Output buffering performance

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?

Answer Source

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;
}