Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Create a Simple Template / View Engine with PHP

3.00/5 (1 vote)
1 Jun 2015CPOL1 min read 28.1K  
How to create a simple template / view engine with PHP

I've always been a fan of code separation. This means; keeping your logic, data model and views strictly separated. I like the way the Yii Framework tackles the separation of views. In Yii, you pass the location of the view and you pass an array of data you want to use in the view and Yii renders the view to a string. The view is in fact just a PHP file. Let's see how it's done.

PHP
<?php
class ViewRenderer{
    public $view_location = "";
    public $data = array();

    public function ViewRenderer($view_location, $data = array()){
        $this->view_location = $view_location;
        $this->data = $data;
    }

    public function render(){
        ob_start();
        include($this->view_location);
        return ob_get_clean();
    }
}
?>

This is the class which does our rendering. The "render()" method of the class returns the actual view. You might see something here that you haven't seen before: "ob_start()" and "ob_get_clean()". Normally, if you use the function "include()", the contents will be directly written to the screen. We don't want that in this case. ob_start() tells the PHP parser to stop buffer all output (e.g. from include or echo). The method ob_get_clean() returns all output which has been buffered from the moment ob_start() has been called. Let's take a look of the script in action.

index.php

PHP
<?php
include('../engine.php');
$data["capitals"] = array(
    array("The Netherlands", "Amsterdam"),
    array("Belgium", "Brussels"),
    array("Sweden", "Stockholm"),
    array("Poland", "Warsaw"),
    array("Hungary", "Budapest"),
    array("USA", "Washington D.C.")
);
$View = new ViewRenderer('view.php', $data);
echo $View->render(); ?>

view.php

PHP
<h1>This is a test view</h1>
<p>
    If you see this, everything seems to work. Now, for some capitals:
</p>
<ul>
    <?php foreach($this->data["capitals"] as $capital): ?>
        <li>The capital of <strong><?php echo $capital[0]; ?></strong> is <strong>
        <?php echo $capital[1]; ?></strong>.</li>
    <?php endforeach; ?>
</ul>

As you can see here, the location of the view and the data are passed to the view renderer object. From within view.php, you can call the passed data array via "$this->data".

There you have it; a very simple but effective way of creating a view engine using PHP.

I've uploaded the source code to GitHub.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)