zpf 视图

时间:2023-03-08 21:00:50

2014年8月19日 18:12:16

smarty使用了2年,

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

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

视图类文件在core/view.php

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

 class _index extends Main
{
public function initc()
{ } public function index()
{
$this->view->a = 111;
$this->view->b = 222;
$this->view->c = 333;
$this->show('test');
}
}

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

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

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

下边是简单的view类

 <?php
/**
* 视图类
*
*/
class View
{
public $prefix = '';
public $module = '';
public $controller = '';
public $action = '';
public $arrSysVar = array(); public function __construct($module, $controller, $action, $arrSysVar)
{
$this->module = $module;
$this->controller = $controller;
$this->action = $action;
$this->arrSysVar = $arrSysVar;
$this->prefix = MODULEPATH.$this->module.'/'.VIEW_FLODER_NAME.'/'.$this->controller.'/';
} //备用初始化
public function init($module, $controller, $action, $arrSysVar)
{
$this->module = $module;
$this->controller = $controller;
$this->action = $action;
$this->arrSysVar = $arrSysVar;
$this->prefix = MODULEPATH.$this->module.'/'.VIEW_FLODER_NAME.'/'.$this->controller.'/';
} //显示到浏览器
//可以重写该方法, 多次调用fetch()来渲染多个页面, 如后台开发的时候,
//顶部/左侧菜单栏/底部 可以统一渲染, 每次只用传入body页面的文件名
public function show($filename)
{
$content = $this->fetch($filename);
// header('Content-Type: ---'.'; charset=utf-8');
// header('Cache-control: ---');
// header('X-Powered-By:zhangzhibin');
echo $content;
} //输出内容到变量
public function fetch($filename)
{
$filename = !empty($filename) ? $filename : $this->action;
$filepath = $this->prefix.$filename.PHP_FILE_EXTENSION; $arrObjViewData = get_object_vars($this);
extract($arrObjViewData); //将普通变量置为全局可访问
extract($this->arrSysVar); //将系统变量置为全局可访问 ob_start();
ob_implicit_flush(0); //渲染传入的模版
require_once($filepath); return ob_end_flush(); //输出到变量, 并清除缓存
}
}