0

I usually use Smarty template engine, so i separate database quesries and other logic from HTML template files, then assign received in PHP variable into Smarty via their function $smarty->assign('variableName', 'variableValue'); then display correct template file with HTML markup, and then i can use within that template my assigned variables.

But how correctly it will be done with .php file tempaltes, without Smarty? For example, i use that construction:

_handlers/Handler_Show.php

$arData = $db->getAll('SELECT .....');
include_once '_template/home.php';

_template/home.php

<!DOCTYPE html>
<html>
<head>
  ....
</head>
<body>
  ...
  <?php foreach($arData as $item) { ?>
    <h2><?=$item['title']?></h2>
  <?php } ?>
  ...
</body>
</html>

It's work. But i heard that it's not the best idea to do that. So is this approach correct? Or maybe there's other way to organize it? Give me advice, pelase.

1 Answer 1

1

Including templates in such a manner like in your example is not best idea because of template code is executed in the same namespace in which it is included. In your case template has access to database connection and other variables which should be separated from view.

In order to avoid this you can create class Template:

Template.php

<?php
class Template
{
    private $tplPath;

    private $tplData = array();

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

    public function __set($varName, $value)
    {
        $this->tplData[$varName] = $value;
    }

    public function render()
    {
        extract($this->tplData);
        ob_start();
        require($this->tplPath);
        return ob_get_clean();
    }
}

_handlers/Handler_Show.php

<?php
// some code, including Template class file, connecting to db etc..
$tpl = new Template('_template/home.php');
$tpl->arData = $db->getAll('SELECT .....');
echo $tpl->render();

_template/home.php

<?php
<!DOCTYPE html>
<html>
<head>
  ....
</head>
<body>
  ...
  <?php foreach($arData as $item): ?>
    <h2><?=$item['title']?></h2>
  <?php endforeach; ?>
  ...
</body>
</html>

As of now template hasn't access to global namespace. Of course it is still possible to use global keyword, or access template object private data (using $this variable), but this is much better solution than including templates directly.

You can look at existing template system source code, for example plates.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.