This is not really a question but I'd like to obtain some opinions about this simple class. For an old project I had the necessity to load some php template files that includes some foreach()
and for()
loops and other variables loaded from a database. I was start thinking how to obtain this using a templating class and this is what I wrote to achieve the objective, I've reworked a templating class that works well with html and php files that doesn't need to load data from variables. I know that I can also use simply the include
, require
or include_once
and require_once
but writing a reusable class was the solution that seemed to me more reliable. Can this class to be considered useful? Is it possible to improve it by using magic methods like __set()
and __get()
to output the desired data to a loop? In the usage example I will not post the $data
variable that is an array of data loaded from database, this choiche is because I don't want to write a long post.
<?php
class Template{
private $tpl;
private $fileName;
private $templatePath;
public function __construct($templatePath){
$this->templatePath = $templatePath;
}
public function loadTemplate(string $tpl){
$this->fileName = basename($tpl.'.php');
if(file_exists($this->templatePath.'/'.$this->fileName)){
return $this->templatePath.'/'.$this->fileName;
} else {
throw new Exception('Template not found.');
}
}
}
?>
Usage example:
<?php
require_once 'Template.class.php';
//$data = array(); this array comes from a db
//$results = array(); this is an handmade array
$template = new Template('path/to/template/file');
include($template->loadTemplate('demo'));
?>
Template file that is loaded
<div class="wrapper">
<?php for($i = 0; $i < count($data); $i++): ?>
<span><small class="text-uppercase"><?php echo $data[$i]['h']; ?></small>
<small> - </small>
<small class="text-uppercase"><?php echo $data[$i]['a']; ?></small>
<p><?php echo $results[mt_rand(1,12)]; ?></p></span>
<?php endfor;?>
</div>