Rate my (really) simple template class

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



So I decided to write a template class in order to get myself going on
learning PHP. Of course I wrote the simplest thing possible:

class Template
{
        protected $template;
        protected $vars;

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

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

        public function __get($name)
        {
                return $this->vars[$name];
        }

        public function __toString()
        {
                ob_start();
                eval('?>' . $this->template);
                return ob_get_clean();
        }
}

Which you can use, quite simply like this:

$tpl = new Template(file_get_contents('index.tpl.php'));

$tpl->title = 'Here\'s the title';
$tpl->text = 'Blah blah blah...';

echo $tpl;

I have a few questions though.

- First, I'm storing the template as an actual string, instead of just
a path to a template file, which means I'm using eval() instead of
require() in my __toString(). My thinking was that this would avoid
reading the template file twice in the case that __toString() gets
called multiple times. But will PHP handle this automagically if I do
in fact decide to store a path to a file, and call require() instead?

- Secondly, I noticed that in the constructor, it's not necessary to
initialize $vars to an empty array, and I haven't done so. I guess PHP
automatically initializes it the first time I set one of its elements
to a value. Is this okay, or is there a better way in the name of best
practices?

- Finally, I'd like to be able to limit what things can be accessed
from the scope of the template file. As it stands, if you have a
function named blowUpTheComputer() or a gobal variable called
$dontTouchThis, a template author can easily cause trouble. They can
also access any methods and properties of the Template class. How
would you go about restricting this?

Thanks a lot!

- BW

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux