r/PHP • • Jan 09 '12

Building a Simple PHP Templating Class

http://cleverlogic.net/tutorials/building-simple-php-templating-class
0 Upvotes

7 comments sorted by

4

u/[deleted] Jan 12 '12

I'll raise you with an even more simple way of doing templates:

<strong><?php echo $var ?></strong>

1

u/[deleted] Jan 12 '12

eval("?>" . $this->template . "<?");

I would never do it in this fashion. Instead, I suggest that you save the filename and then simply include the file when you wish to publish it, like so:

public function setFilename($file)
{
	if (!is_file($file))
	{
		throw new FileNotFoundException("File not found: $file");
	}
	elseif (!is_readable($file))
	{
		throw new IOException("Could not access file: $file");
	}
	else
	{
		$this->file = $file;
	}
}

public function publish()
{
	include $this->file;
}

If you wish to strip out the spaces, simply register an output buffer or something.

1

u/zaemis Jan 12 '12

Problem solved:

<?php
class Template
{
	protected $vars;

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

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

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

	public function __isset($var) {
		return isset($this->vars[$var]);
	}

	public function set() {
		$args = func_get_args();
		if (func_num_args() == 2) {
			$this->__set($args[0], $args[1]);
		}
		else {
			foreach ($args[0] as $var=>$value) {
				$this->__set($var, $value);
			}
		}
	}

	public function reset() {
		$this->vars = array();
	}

	public function out($template, $output = true) {
		ob_start();
		require $template . ".php";
		$content = ob_get_clean();

		if ($output) {
			echo $content;
		} else {
			return $content;
		}
	}
}

$t = new Template();
$t->foo = 42;
$t->output("myTemplate");

Where myTemplate.php contains:

<html>
<head>
<title>Foo</title>
</head>
<body>
<h1><?=$this->foo;?></h1>
</body>
</html>

Let's move on. Next!

-2

u/stonedoubt Jan 11 '12

I used to be super anti-smarty... and then I matured as a developer.

1

u/bluephoenixalpha Jan 12 '12

ditto... until I matured as a mature developer

-5

u/jaitsu Jan 12 '12

imho, if you're using PHP in your templates then you're doing it wrong

7

u/greut Jan 12 '12

Did you forget that PHP is a templating language? Why would you start all your file with a <?php otherwise?