Using PHP output buffering as a CMS template solution

  / Leave a comment

I recently came upon a couple new PHP functions, ob_start() and ob_get_clean(). These functions take advantage of PHP’s internal output buffer and allows the programmer access to all output generated during execution.

I was able to structure a template architecture using these functions. My CMS architecture can incorporate a new page by simply adding a .php file with two lines of code.

<?php include_once('assets/template.php'); // Load website functions. ?>
<!-- Any HTML placed here will be wrapped in the template -->
<?php build_template('Welcome to the website!', 'home'); // Build template using buffered output. ?>

This can work gracefully because all necessary custom PHP functions are loaded within the first required line of code; include_once(‘assets/template.php’). So essentially I write all the page content to the output buffer then wrap it with the template header and footer before execution completes. To capture the buffered content I placed an ob_start() at the beginning of template.php thus after it loads, all output will be buffered.

output-buffer

The second required line needs to be called only after all data has been finished buffering. build_template() gets the string representation of the buffered content and concatenates it with the header and footer. ob_get_clean() simultaneously clears the buffer. Here is what the build_template() function looks like.

function build_template($title, $page_alias, $auth = false) {
    // Get the login result
    GLOBAL $login_result;

    // Get header.
    $markup = get_header($title, $page_alias);

    // Prep the page content
    $html = wrap_page_container(ob_get_clean());

    // Check if user needs to be logged in.
    if ($auth) {
        $markup .= (is_logged_in()) ? $html : wrap_page_container(show_login($login_result));
    } else {
        $markup .= $html;
    }

    // Get footer.
    $markup .= get_footer();
    echo $markup;
}

Leave a Comment

* required

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>