Home

Algorithmic Advent: 07 – A very basic templating solution

Published on 7 Dec 2010. Tagged with php, algorithmicadvent.

One major design goal when building a web application is the separation of business logic and presentation. A simple way to achieve this are „View“ classes which act as an interface between the application's data model and for instance HTML template scripts that are used to render the output.

The following example shows a very basic implementation of this concept.

/**
 * A very simple View class
 */
class SimpleView
{
    /**
     * @var array Stores data for the template script
     */
    protected $vars = array();

    /**
     * Sets a template variable
     *
     * @param string $name
     * @param string $value
     */
    public function __set($name, $value)
    {
        $this->vars[$name] = $value;
    }

    /**
     * Gets a template variable
     *
     * @param string $name
     * @return string|null
     */
    public function __get($name)
    {
        return (isset($this->vars[$name])) ? $this->vars[$name] : null;
    }

    /**
     * Renders a template script
     *
     * @param string $template
     */
    public function render($template)
    {
        include $template;
    }
}

Usage example:

$view = new SimpleView();

$view->heading = 'Hello World!';
$view->content = 'Here\'s some content.';

$tmp = array();
for ($i = 0; $i < 10; $i++) {
    $tmp[] = 'Test ' . $i;
}
$view->someMoreData = $tmp;

$view->render('test.phtml');

The corresponding template file (test.pthml):

<h1><?php echo $this->heading; ?></h1>
<p><?php echo $this->content; ?></p>

<ul>
<?php foreach ($this->someMoreData as $data) : ?>
    <li><?php echo $data; ?></li>
<?php endforeach; ?>
</ul>