PHP: View template class

Sean Wragg
Sean’s Blog
Published in
2 min readMar 18, 2008

Below, I’ve created a very simple view template class. Similar to the ever popular Smarty framework, although not nearly as big or feature rich. Typically you would use this to separate design from code (mvc pattern), which makes things much easier to manage over time. Another use for this would be to have dynamic template system; if used correctly users would be able to pick/manage provided templates.

This class essentially requires three files:

  1. The template class itself — template.class.php
  2. A file to consume the class — example.php
  3. A view template file which will hold the html layout and variables that we will define within the consumer. — example.html
<?php  
/**
* @author Sean Wragg <seanwragg@gmail.com>
* @version 1.0 template.class.php
*/

class Template {
protected $file;
public $values;

// attempt to locate file upon instantiation
function __construct( $file ) {
if (!file_exists( $file )) die('unable to locate file');
$this->file = $file;
}

// arg must be an array
public function set( $values ) {
foreach( $values as $key => $value ) {
$this->values[$key] = $value;
}
}

// render's html with keys replaced
public function renderHTML() {
$contents = file_get_contents( $this->file );
foreach( $this->values as $key => $value ) {
$contents = str_replace('[@'. $key .']', $value, $contents);
}
echo $contents;
}
}

As you can see, there are two functions within the template class that handle everything: set() and renderHTML(). Anything passed to set() needs to be in array format; where as the array keys are directly translated into the variables we will use to call within our html template file.

When instantiating Template, argument needs to be the location of the html file we intend to use for our layout. once we’ve done that simply call renderHTML()

Now that we have our template class and an idea for how it works, we should create a file to reference it.

// file: example.php
include 'template.class.php';
$template = new Template('example.html');

$args = array(
'WOULD' => 'would be',
'EXAMPLE' => 'an awesome <i>example</i>'
);

$template->set($args);
$template->renderHTML();

After that we can now work on our layout (view) file. Here we reference the array keys previously set within our example.php.

<!-- file: example.html -->  
<html>
<body>This [@WOULD] [@EXAMPLE.]</body>
</html>

Done!

The result of everything posted above should be:

This would be an awesome <i>example</i>.

Originally published at seanwragg.com on March 18, 2008.

--

--