4. 模板引擎源码文件
1 <?php
2 /**
3 * DsTemplate 模板类
4 *
5 * @filesource DsTemplate.class.php
6 * @package DsTemplate
7 * @subpackage
8 * @version $id: 0.2, utf8, Fri Jan 1 15:30:11 CST 2010
9 * @author LD King <kldscs[at]gmail.com>
10 * @copyright Copyleft (D.) 2007 – 2009 MiFunny China Inc.
11 * @link http://mifunny.info/
12 * @see example: testView.php
13 */
14 class DsTemplate{
15 private static $_instance;
16 //private $_tp = null; //模板根目录
17 //private $_content = null; //最后显示的内容
18
19 /**
20 * 变量数组
21 * TEMPLATEPATH 模板根目录
22 *
23 * @var array
24 */
25 private $_vars = array(
26 ’TEMPLATEPATH‘ => null,
27 );
28
29 /**
30 * 初始化 模板引擎
31 *
32 * @param string 模板根目录
33 */
34 public function __construct($template_path = null){
35 if( is_string($template_path) ){
36 $this->_vars['TEMPLATEPATH'] = $template_path;
37 }
38 self::$_instance = $this;
39 }
40
41 /**
42 * 重写魔法方法 __set 和 __get
43 *
44 * @param string $key
45 * @param mixed $value
46 */
47 public function __set($key, $value){
48 $this->_vars[$key] = $value;
49 }
50
51 public function __get($key){
52 return $this->_vars[$key];
53 }
54
55 /**
56 * 获得最后的显示信息
57 *
58 * @param string $template 模板文件全名
59 */
60 public function fetch($template){
61 //目录分隔符
62 if( !defined(‘DS‘) ) define(‘DS‘, DIRECTORY_SEPARATOR);
63 //模板根目录
64 if( !defined(‘TP‘) ) define(‘TP‘, empty($this->_vars['TEMPLATEPATH']) ? ” : rtrim($this->_vars['TEMPLATEPATH'], ‘\\/‘).DS );
65
66 $template = TP.str_replace(‘/‘, DS, $template);
67 if( is_file($template) ){
68 unset( $this->_vars['TEMPLATEPATH'] );
69 extract($this->_vars, EXTR_OVERWRITE);
70
71 $errno = error_reporting();
72 error_reporting($errno & ~E_NOTICE);
73 ob_start();
74 include($template);
75 $content = ob_get_contents();
76 ob_end_clean();
77 error_reporting($errno);
78
79 return $content;
80 }else{
81 throw new LogicException(‘(‘.__CLASS__.‘->‘.__METHOD__.‘)‘.‘Error: ‘.$template.‘ is not a file !‘);
82 return false;
83 }
84 }
85
86 public function display($template){
87 echo $this->fetch($template);
88 }
89
90 /**
91 * 获得静态视图对像
92 *
93 * @return object DsTemplate
94 */
95 public static function getInstance(){
96 if( !(self::$_instance instanceof self) ){
97 new self(); // self::$_instance = new self();
98 }
99 return self::$_instance;
100 }
101
102 /**
103 * 静态方法, 显示视图
104 *
105 * @param string $template 模板文件
106 * @param array $vars 变量数组
107 */
108 public static function show($template, array $vars=null){
109 $view = self::getInstance();
110 //$view->TEMPLATEPATH = $template_path;
111 if( !empty($vars) ){
112 $view->_vars = $vars;
113 }
114 $view->display($template);
115 }
116
117 }//END class DsTemplate
118
119 /**
120 * 显示变量
121 *
122 * @param mixed $value 需显示的变量, 字符串 or 数字
123 * @param bool $escape 是否转义
124 */
125 function _e($value, $escape=true){
126 if($escape and is_string($value) ){
127 echo htmlspecialchars($value, ENT_QUOTES);
128 }else{
129 echo $value;
130 }
131 }//END func _e
132 ?>
最新评论