abstract
Code: Select all
<?php
abstract class Template_Abstract
{
private $_data = array();
private $_option = array('dir' => '');
public function __construct()
{
$this->_config();
}
public function assign($name, $value)
{
$this->_data[$name] = $value;
return $this;
}
public function display($template, $buffer = true)
{
extract($this->_data);
if ($buffer)
ob_start();
$path = $this->getPath($template);
if (!file_exists($path))
throw new Template_Exception(3);
else
require $path;
if ($buffer)
return ob_get_clean();
return true;
}
protected function setDir($dir)
{
if (!file_exists($dir) && $dir)
throw new Template_Exception(2);
$this->_option['dir'] = $dir;
}
protected function __get($name)
{
if ($this->__isset($name))
return $this->_data[$name];
else
throw new Template_Exception(4);
}
protected function __isset($name)
{
if (isset($this->_data[$name]))
return true;
}
protected function __unset($name)
{
if ($this->__isset($name))
{
unset($this->_data[$name]);
return true;
}
}
protected function __set($name, $value)
{
return $this->_data[$name] = $value;
}
protected function _config()
{
}
protected function _debug($data)
{
return $data;
}
protected function _debugDisplay($data)
{
echo "<pre>\n";
print_r($data);
echo "</pre>";
}
protected function debug()
{
$this->_debugDisplay($this->_debug($this->_data));
}
protected function getDir()
{
return $this->_option['dir'];
}
protected function getPath($file)
{
if ($file[strlen($file) - 1] == '/')
{
$dir = $dir = $this->getDir();
}
else
{
if (strlen($this->getDir()) != 0)
$dir = $this->getDir() . '/';
else
$dir = '';
}
return $dir . $file;
}
public function clear()
{
$this->_data = array();
}
}
?>Code: Select all
<?php
class Template_Exception extends Exception
{
public function __construct($code)
{
switch ($code):
case 1:
$message = 'template directory is not set';
break;
case 2:
$message = 'template directory does not exist';
break;
case 3:
$message = 'tempalte file does not exist';
break;
case 4:
$message = 'that template variable has not been set';
break;
default:
$message = 'unknown template exception';
break;
endswitch;
parent::__construct($message, $code);
}
}
?>Code: Select all
<?php
class Template extends Template_Abstract
{
public function _config()
{
$this->setDir($_SERVER['DOCUMENT_ROOT'] . '/' . 'templates');
}
}
?>Code: Select all
<?php
function template()
{
static $template = false;
if ($template == false)
$template = new Template();
else
$template->clear();
return $template;
}
?>Code: Select all
echo template()->assign('one', 'two')
->assign('three', 'four')
->display('some_file.tpl');Code: Select all
template()->assign('one', 'two')
->assign('three', 'four')
->display('some_file.tpl', false);