码迷,mamicode.com
首页 > 其他好文 > 详细

增强CI的前端展示层

时间:2014-09-23 11:06:54      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:style   http   io   os   ar   for   文件   数据   div   

CodeIgniter 很适合小站点应用开发,但是它自带的view功能可能会给不懂PHP的前端人员带来麻烦。 相比之下phpcms的view模板解析就强大多了,所以这里就把PHPCMS的模板解析功能剥离出来,加到PHPCMS上。

首先在CodeIgniter libraries中 增加 template_cache.php老品牌娱乐城

001 <?php if (!defined(‘BASEPATH‘)) exit(‘No direct script access allowed‘);
002 /**
003 *  模板解析缓存
004 */
005 final class template_cache {
006    
007     public $cache_path;
008     public function __construct()
009     {
010         //$CI =& get_instance();
011         $this->cache_path = APPPATH.‘views‘;
012     }
013    
014     /**
015      * 编译模板
016      *
017      * @param $module    模块名称
018      * @param $template    模板文件名
019      * @param $istag    是否为标签模板
020      * @return unknown
021      */
022    
023     public function template_compile($module, $template, $style = ‘default‘) {
024        
025         $tplfile= APPPATH.‘views‘.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.‘.php‘;
026        
027         if (! file_exists ( $tplfile )) {
028             show_error($tplfile ,  500 ,  ‘Template does not exist(1)‘);
029         }
030        
031         $content = @file_get_contents ( $tplfile );
032  
033         $filepath = $this->cache_path.DIRECTORY_SEPARATOR.‘caches_template‘.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR;
034        
035        
036         if(!is_dir($filepath)) {
037             mkdir($filepath, 0777, true);
038         }
039         $compiledtplfile = $filepath.$template.‘.php‘;
040         $content = $this->template_parse($content);
041         $strlen = file_put_contents ( $compiledtplfile, $content );
042         chmod ( $compiledtplfile, 0777 );
043         return $strlen;
044     }
045    
046     /**
047      * 更新模板缓存
048      *
049      * @param $tplfile    模板原文件路径
050      * @param $compiledtplfile    编译完成后,写入文件名
051      * @return $strlen 长度
052      */
053     public function template_refresh($tplfile, $compiledtplfile) {
054         $str = @file_get_contents ($tplfile);
055         $str = $this->template_parse ($str);
056         $strlen = file_put_contents ($compiledtplfile, $str );
057         chmod ($compiledtplfile, 0777);
058         return $strlen;
059     }
060    
061  
062     /**
063      * 解析模板
064      *
065      * @param $str    模板内容
066      * @return ture
067      */
068     public function template_parse($str) {
069         $str = preg_replace ( "/\{template\s+(.+)\}/", "<?php include template(\\1); ?>", $str );
070         $str = preg_replace ( "/\{include\s+(.+)\}/", "<?php include \\1; ?>", $str );
071         $str = preg_replace ( "/\{view\s+(.+)\}/", "<?php \$this->load->view(\\1); ?>", $str );
072         $str = preg_replace ( "/\{php\s+(.+)\}/", "<?php \\1?>", $str );
073         //alex fix
074         $str = preg_replace ( "/\{{if\s+(.+?)\}}/", "``if \\1``", $str );
075         $str = preg_replace ( "/\{{else\}}/", "``else``", $str );
076         $str = preg_replace ( "/\{{\/if\}}/", "``/if``", $str );
077        
078         $str = preg_replace ( "/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str );
079         $str = preg_replace ( "/\{else\}/", "<?php } else { ?>", $str );
080         $str = preg_replace ( "/\{elseif\s+(.+?)\}/", "<?php } elseif (\\1) { ?>", $str );
081         $str = preg_replace ( "/\{\/if\}/", "<?php } ?>", $str );
082        
083         //for 循环
084         $str = preg_replace("/\{for\s+(.+?)\}/","<?php for(\\1) { ?>",$str);
085         $str = preg_replace("/\{\/for\}/","<?php } ?>",$str);
086         //++ --
087         $str = preg_replace("/\{\+\+(.+?)\}/","<?php ++\\1; ?>",$str);
088         $str = preg_replace("/\{\-\-(.+?)\}/","<?php ++\\1; ?>",$str);
089         $str = preg_replace("/\{(.+?)\+\+\}/","<?php \\1++; ?>",$str);
090         $str = preg_replace("/\{(.+?)\-\-\}/","<?php \\1--; ?>",$str);
091         //alex fix
092         $str = preg_replace ( "/\``if\s+(.+?)\``/", "{{if \\1}}", $str );
093         $str = preg_replace ( "/\``else``/", "{{else}}", $str );
094         $str = preg_replace ( "/\``\/if\``/", "{{/if}}", $str );
095        
096         $str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\}/", "<?php \$n=1;if(is_array(\\1)) foreach(\\1 AS \\2) { ?>", $str );
097         $str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php \$n=1; if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>", $str );
098         $str = preg_replace ( "/\{\/loop\}/", "<?php \$n++;}unset(\$n); ?>", $str );
099         $str = preg_replace ( "/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
100         $str = preg_replace ( "/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
101         $str = preg_replace ( "/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \\1;?>", $str );
102         $str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\‘\"\$\x7f-\xff]+)\}/es", "\$this->addquote(‘<?php echo \\1;?>‘)",$str);
103         $str = preg_replace ( "/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str );
104         $str = preg_replace("/\{pc:(\w+)\s+([^}]+)\}/ie", "self::pc_tag(‘$1‘,‘$2‘, ‘$0‘)", $str);
105         $str = preg_replace("/\{\/pc\}/ie", "self::end_pc_tag()", $str);
106         $str = "<?php defined(‘BASEPATH‘) or exit(‘No direct script access allowed.‘); ?>" . $str;
107         return $str;
108     }
109  
110     /**
111      * 转义 // 为 /
112      *
113      * @param $var    转义的字符
114      * @return 转义后的字符
115      */
116     public function addquote($var) {
117         return str_replace ( "\\\"", "\"", preg_replace ( "/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "[‘\\1‘]", $var ) );
118     }
119    
120     /**
121      * 解析PC标签
122      * @param string $op 操作方式
123      * @param string $data 参数
124      * @param string $html 匹配到的所有的HTML代码
125      */
126     public static function pc_tag($op, $data, $html) {
127         preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);
128         $arr = array(‘action‘,‘num‘,‘cache‘,‘page‘, ‘pagesize‘, ‘urlrule‘, ‘return‘, ‘start‘,‘setpages‘);
129         $tools = array(‘json‘, ‘xml‘, ‘block‘, ‘get‘);
130         $datas = array();
131         $tag_id = md5(stripslashes($html));
132         //可视化条件
133         $str_datas = ‘op=‘.$op.‘&tag_md5=‘.$tag_id;
134         foreach ($matches as $v) {
135             $str_datas .= $str_datas ? "&$v[1]=".($op == ‘block‘ && strpos($v[2], ‘$‘) === 0 ? $v[2] : urlencode($v[2])) : "$v[1]=".(strpos($v[2], ‘$‘) === 0 ? $v[2] : urlencode($v[2]));
136             if(in_array($v[1], $arr)) {
137                 $$v[1] = $v[2];
138                 continue;
139             }
140             $datas[$v[1]] = $v[2];
141         }
142         $str = ‘‘;
143         $setpages = isset($setpages) && intval($setpages) ? intval($setpages) : 10;
144         $num = isset($num) && intval($num) ? intval($num) : 20;
145         $cache = isset($cache) && intval($cache) ? intval($cache) : 0;
146         $return = isset($return) && trim($return) ? trim($return) : ‘data‘;
147         if (!isset($urlrule)) $urlrule = ‘‘;
148         if (!empty($cache) && !isset($page)) {
149             $str .= ‘$tag_cache_name = md5(implode(\‘&\‘,‘.self::arr_to_html($datas).‘).\‘‘.$tag_id.‘\‘);if(!$‘.$return.‘ = tpl_cache($tag_cache_name,‘.$cache.‘)){‘;
150         }
151         if (in_array($op,$tools)) {
152             switch ($op) {
153                 case ‘json‘:
154                         if (isset($datas[‘url‘]) && !empty($datas[‘url‘])) {
155                             $str .= ‘$json = @file_get_contents(\‘‘.$datas[‘url‘].‘\‘);‘;
156                             $str .= ‘$‘.$return.‘ = json_decode($json, true);‘;
157                         }
158                     break;
159                    
160                 case ‘block‘:
161                     $str .= ‘$block_tag = pc_base::load_app_class(\‘block_tag\‘, \‘block\‘);‘;
162                     $str .= ‘echo $block_tag->pc_tag(‘.self::arr_to_html($datas).‘);‘;
163                     break;
164             }
165         } else {
166             if (!isset($action) || empty($action)) return false;
167             if ( file_exists(APPPATH.‘libraries‘.DIRECTORY_SEPARATOR.$op.‘_tag.php‘)) {
168                 $str .= ‘if(!isset($CI))$CI =& get_instance();$CI->load->library("‘.$op.‘_tag");if (method_exists($CI->‘.$op.‘_tag, \‘‘.$action.‘\‘)) {‘;   
169                 if (isset($start) && intval($start)) {
170                     $datas[‘limit‘] = intval($start).‘,‘.$num;
171                 } else {
172                     $datas[‘limit‘] = $num;
173                 }
174                 if (isset($page)) {
175                     $str .= ‘$pagesize = ‘.$num.‘;‘;
176                     $str .= ‘$page = intval(‘.$page.‘) ? intval(‘.$page.‘) : 1;if($page<=0){$page=1;}‘;
177                     $str .= ‘$offset = ($page - 1) * $pagesize;$urlrule="‘.$urlrule.‘";‘;
178                     $datas[‘limit‘] = ‘$offset.",".$pagesize‘;
179                     $datas[‘action‘] = $action;
180                     $str .= ‘$‘.$op.‘_total = $CI->‘.$op.‘_tag->count(‘.self::arr_to_html($datas).‘);‘;
181                    
182                     $str .= ‘if($‘.$op.‘_total>$pagesize){ $pages = pages($‘.$op.‘_total, $page, $pagesize, $urlrule); } else { $pages="" ;}‘;
183                 }
184                 $str .= ‘$‘.$return.‘ = $CI->‘.$op.‘_tag->‘.$action.‘(‘.self::arr_to_html($datas).‘);‘;
185                 $str .= ‘}‘;
186             }
187         }
188         if (!empty($cache) && !isset($page)) {
189             $str .= ‘if(!empty($‘.$return.‘)){setcache($tag_cache_name, $‘.$return.‘, \‘tpl_data\‘);}‘;
190             $str .= ‘}‘;
191         }
192         return "<"."?php ".$str."?".">";
193     }
194    
195     /**
196      * PC标签结束
197      */
198     static private function end_pc_tag() {
199         return ‘<?php if(defined(\‘IN_ADMIN\‘) && !defined(\‘HTML\‘)) {if(isset($data))unset($data);echo \‘</div>\‘;}?>‘;
200     }
201    
202     /**
203      * 转换数据为HTML代码
204      * @param array $data 数组
205      */
206     private static function arr_to_html($data) {
207         if (is_array($data)) {
208             $str = ‘array(‘;
209             foreach ($data as $key=>$val) {
210                 if (is_array($val)) {
211                     $str .= "‘$key‘=>".self::arr_to_html($val).",";
212                 } else {
213                     if (strpos($val, ‘$‘)===0) {
214                         $str .= "‘$key‘=>$val,";
215                     } else {
216                         $str .= "‘$key‘=>‘".self::new_addslashes($val)."‘,";
217                     }
218                 }
219             }
220             return $str.‘)‘;
221         }
222         return false;
223     }
224    
225     /**
226      * 返回经addslashes处理过的字符串或数组
227      * @param $string 需要处理的字符串或数组
228      * @return mixed
229      */
230     function new_addslashes($string){
231         if(!is_array($string)) return addslashes($string);
232         foreach($string as $key => $val) $string[$key] = new_addslashes($val);
233         return $string;
234     }
235 }

然后在global_helper中增加一个 template函数

01 if ( ! function_exists(‘template‘))
02 {
03     /**
04      * 模板调用
05      *
06      * @param $module
07      * @param $template
08      * @param $istag
09      * @return unknown_type
10      */
11     function template($module = ‘expatree‘, $template = ‘index‘, $style = ‘expatree‘,$return_full_path=true) {
12         global $CI;
13         if(!isset($CI))$CI =& get_instance();
14         if(!$style) $style = ‘default‘;
15         $CI->load->library(‘template_cache‘,‘template_cache‘);
16         $template_cache = $CI->template_cache;
17         //编译模板生成地址
18         $compiledtplfile = $template_cache->cache_path.DIRECTORY_SEPARATOR.‘caches_template‘.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.EXT;
19         //视图文件
20         $tplfile= APPPATH.‘views‘.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.EXT;
21         if(file_exists($tplfile)) {
22             if(!file_exists($compiledtplfile) || (@filemtime($tplfile) > @filemtime($compiledtplfile))) {   
23                 $template_cache->template_compile($module, $template, $style);
24             }
25         } else {
26             //如果没有就调取默认风格模板
27             $compiledtplfile = $template_cache->cache_path.DIRECTORY_SEPARATOR.‘caches_template‘.DIRECTORY_SEPARATOR.‘default‘.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.EXT;
28             if(!file_exists($compiledtplfile) || (file_exists($tplfile) && filemtime($tplfile) > filemtime($compiledtplfile))) {
29                 $template_cache->template_compile($module, $template, ‘default‘);
30             } elseif (!file_exists($tplfile)) {
31                 show_error($tplfile ,  500 ,  ‘Template does not exist(0)‘);
32             }
33         }
34  
35         if($return_full_path)
36             return $compiledtplfile;
37         else
38             return ‘caches_template‘.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template;
39     }
40 }

然后在MY_Controller.php,增加一个方法

01 /**
02 * 自动模板调用
03 *
04 * @param $module
05 * @param $template
06 * @param $istag
07 * @return unknown_type
08 */
09 protected function view($view_file,$page_data=false,$cache=false)
10 {
11     $view_file=$this->template($this->page_data[‘controller_name‘].$this->page_data[‘module_name‘],$view_file);
12    
13     $this->load->view($view_file,$page_data);
14 }

这样基本上完成了,可以直接phpcms模板语法了。

增强CI的前端展示层

标签:style   http   io   os   ar   for   文件   数据   div   

原文地址:http://www.cnblogs.com/laoyangman/p/3987583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!