1
\$\begingroup\$

I tried writing my very first template engine today. I designed it to just replace variables in templates, and keep it basic for now. Can anyone give me some constructive criticism?

I'm getting ready to write my own mini framework, and want to improve as much as I can. I just need to know if this is the default way (logic) to write one, or is there a better way?

<?php 

class Template {

    public $variables = [];

    public function assign($key, $value) {
        $this->variables[$key] = $value;
    }

    public function render($template, $variables = []) {
        if (empty($variables)) {
            $variables = $this->variables;
        }

        $code = file_get_contents($template);

        foreach ($this->variables as $key => $variable) {
            $code = str_replace('%' . $key . '%', $this->variables[$key], $code);
        }

        return $code;
    }
}
\$\endgroup\$
  • \$\begingroup\$ I'm not sure you're handing the variables in a clever way. What if you want to use the assign() method, but supply some more variable to render() at the same time? Why not merge the two arrays so you can use both? \$\endgroup\$ – KIKO Software Nov 29 '18 at 1:04
  • \$\begingroup\$ Id put this down to design preference, personal preference that is but its an interesting point which I share with you. I'm looking to make the code better, not different. But I do agree that this would probably be a better design choice. \$\endgroup\$ – Beefo Nov 29 '18 at 2:21
0
\$\begingroup\$

This template is either unusable or would make you write HTML in the business logic part spoiling the whole idea.

A template engine is a more complex application than people often think. There is always a presentation logic that could be quite complex. Which means a template must support programming statements. At least loops and conditions. Without them, it will be almost unusable.

Imagine you need to list 10 posts an a blog. How it could be done in your template? Going to add all the HTML formatting to variables before assigning them? Really?

So, such a simple template could be made viable only by letting PHP to interpret the template. So it could be like

public function render($template, $variables = []) {
    array_merge($this->variables, $variables);
    extract($variables)
    ob_start();
    include $template;
    return ob_get_clean();
}

this way you will be able to use full featured templates that will contain all the logic needed for the presentation of your data.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.