zpf 视图

2014年8月19日 18:12:16

smarty使用了2年,

使用PHP本身做模版引擎也有4个多月了,

最终还是在我的这个框架中抛弃了smarty,转用原生的PHP代码做模版引擎,并简单写了一个视图类,还没有实现缓存功能

视图类文件在core/view.php

控制器中的使用方法(代码在current_module/controller/xxx.php):

 1 class _index extends Main
 2 {
 3     public function initc()
 4     {    }
 8 
 9     public function index()
10     {
11         $this->view->a = 111;
12         $this->view->b = 222;
13         $this->view->c = 333;
14         $this->show('test');
15     }
16 }

模版中使用变量(模版放在current_module/views/current_controller/test.php):

<?= $a, $b, $c ?>

模版中完全使用PHP的语法规则,不像smarty中又定义了一套语法规则

下边是简单的view类

 1 <?php
 2 /**
 3  * 视图类
 4  * 
 5  */
 6 class View 
 7 {
 8     public $prefix = '';
 9     public $module = '';
10     public $controller = '';
11     public $action = '';
12     public $arrSysVar = array();
13     
14     public function __construct($module, $controller, $action, $arrSysVar)
15     {
16         $this->module         = $module;
17         $this->controller     = $controller;
18         $this->action         = $action;
19         $this->arrSysVar     = $arrSysVar;
20         $this->prefix         = MODULEPATH.$this->module.'/'.VIEW_FLODER_NAME.'/'.$this->controller.'/';
21     }
22     
23     //备用初始化
24     public function init($module, $controller, $action, $arrSysVar)
25     {
26         $this->module         = $module;
27         $this->controller     = $controller;
28         $this->action         = $action;
29         $this->arrSysVar     = $arrSysVar;
30         $this->prefix         = MODULEPATH.$this->module.'/'.VIEW_FLODER_NAME.'/'.$this->controller.'/';
31     }
32 
33     //显示到浏览器
34     //可以重写该方法, 多次调用fetch()来渲染多个页面, 如后台开发的时候,
35     //顶部/左侧菜单栏/底部 可以统一渲染, 每次只用传入body页面的文件名
36     public function show($filename)
37     {
38         $content = $this->fetch($filename);
39         // header('Content-Type: ---'.'; charset=utf-8');
40         // header('Cache-control: ---');
41         // header('X-Powered-By:zhangzhibin');
42         echo $content;
43     }
44     
45     //输出内容到变量
46     public function fetch($filename)
47     {
48         $filename = !empty($filename) ? $filename : $this->action;
49         $filepath = $this->prefix.$filename.PHP_FILE_EXTENSION;
50         
51         $arrObjViewData = get_object_vars($this);
52         extract($arrObjViewData); //将普通变量置为全局可访问
53         extract($this->arrSysVar); //将系统变量置为全局可访问
54 
55         ob_start();
56         ob_implicit_flush(0);
57 
58         //渲染传入的模版
59         require_once($filepath);
60 
61         return ob_end_flush(); //输出到变量, 并清除缓存 
62     }
63 }
原文地址:https://www.cnblogs.com/iLoveMyD/p/3922852.html