Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to write a PHP template class - this feels wrong

Tags:

php

templates

I'm trying to learn a few things about PHP and write my own template class. But it just feels ineffective. Wouldn't performance take a hit from doing this? If you can, take a look and see what's wrong:

<?

class Template {

    private $file, $template, $data;

    public function __construct($file) {
            $this->template = file_get_contents('views/wrapper.php');
            $this->file = file_get_contents('views/'.$file.'.php');
    }

    public function __set($key, $val) { $this->data[$key] = $val; }

    public function __get($key) { return $this->data[$key]; }

    private function replaceAll() {
        foreach($this->data AS $key => $val)
            $this->template = str_replace('@'.$key, $val, $this->template);
        $this->template = str_replace('{LOAD}', $this->file, $this->template);
    }

    public function render() {
        $this->replaceAll();
        echo $this->template;
    }
}

?>

I want to use a wrapper, that holds the footer + header, which contain a sidebar/navigation. So I'll need to somehow dynamically set an active class there, and then I want to be able to load the view based on the constructor or something similar. Is what I'm doing.. okay?

like image 885
Brooklyn Nicholson Avatar asked Jan 01 '26 00:01

Brooklyn Nicholson


1 Answers

__get and __set functions are very slow. string replacements are pretty slow as well. why are you making your template in this way? what if you did something more like this?

template class

class template {

   protected $templateFile;

   public function __construct($template_file) {
      $this->templateFile = $template_file;
   }

   public function render() {
      require($this->templateFile);
   }
}

template file

<html>
   <p><?= $this->someProperty ?></p>
</html>

usage

$view = new template($template_file_path);
$view->someProperty = 'hello world';
$view->render();

only drawback would be that whoever writes the templates would also have access to writing PHP.

like image 144
dqhendricks Avatar answered Jan 02 '26 13:01

dqhendricks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!