Prosta klasa szablonów w PHP

by Nazgul

Stwo­rzy­łem tą klasę jakiś czas temu, na wła­sny uży­tek, i stwier­dzi­łem, że dosko­nale zastę­puje inne tego typu klasy. Skład­nia sza­blo­nów wygląda tak jak w word­pres­sie, czyli zwy­kły kod php, osa­dzony w szablonach.

Jeśli masz pomysł jak ulep­szyć tą klasę, dodać nową funk­cjo­nal­ność, lub po pro­stu zna­la­złeś błąd, pro­szę o kon­takt ;) Å»yczę miłego używania!

Wer­sja do ściągnięcia/skopiowania.

< ?php
/* * * * * * * * * * * *

Licenced for use under the LGPL. See http://www.gnu.org/licenses/lgpl-3.0.txt.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This licence is there: http://www.gnu.org/licenses/lgpl-3.0.txt.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS /FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

* * * * * * * * * * * * */

/*
 * Filename: templates.class.php
 * Author: Dawid "nazgul" Dziurdzia
 * Licence: LGPL v3.0
 */

class Template
{
    protected $_path;
    protected $_vars = array();
    protected $_result;

    public function Template($path)
    {
        $this->_path = $path;
    } //end constructor

    public function set($name, $value)
    {
        if(!isset($this->_vars[$name]))
        {
            $this->vars[$name] = $value;
        }
    } //end set()

    public function renderTemplate()
    {
        ob_start(); //włączamy buforowanie

        $filename = $this->_path;
        $keys = array_keys($this->vars);

        for ($i=0; $ivars); $i++) //pętla po elementach $vars (przypisujemy zmiennym ($key) wartości z tablicy)
        {
            $key = $keys[$i];
            global ${$key};
            ${$key} = $this->vars[$key];
        }		

        // require_once('/inc/template_helper.php');  //dołączamy plik z funkcajmi pomocniczymi
        require_once($filename); //przetwarzamy plik szablonu

        $output = ob_get_contents(); //pobieramy zawartość bufora do zmiennej

        ob_end_clean(); //kończymy buforować

        $this->_result = $output();
    } //end renderTemplate()

    public function printTemplate()
    {
         echo $this->_result; //wypisujemy rezultat na ekran
    } //end printTemplate()

} //end Template

?>