123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- <?php
- namespace daswork;
- class View
- {
- // 视图实例
- protected static $instance;
- // // 模板引擎实例
- // public $engine;
- // 模板变量
- protected $data = [];
- // 用于静态赋值的模板变量
- protected static $var = [];
- // // 视图输出替换
- // protected $replace = [];
- // /**
- // * 构造函数
- // * @access public
- // * @param array $engine 模板引擎参数
- // * @param array $replace 字符串替换参数
- // */
- // public function __construct($engine = [], $replace = [])
- // {
- // //基础替换字符串
- // $request = Request::instance();
- // $base = $request->root();
- // $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
- // if ('' != $root) {
- // $root = '/' . ltrim($root, '/');
- // }
- // $baseReplace = [
- // '__ROOT__' => $root,
- // '__URL__' => $base . '/' . $request->module() . '/' . Loader::parseName($request->controller()),
- // '__STATIC__' => $root . '/static',
- // '__CSS__' => $root . '/static/css',
- // '__JS__' => $root . '/static/js',
- // ];
- // $this->replace = array_merge($baseReplace, (array) $replace);
- // }
- // /**
- // * 初始化视图
- // * @access public
- // * @param array $engine 模板引擎参数
- // * @param array $replace 字符串替换参数
- // * @return object
- // */
- // public static function instance($engine = [], $replace = [])
- // {
- // if (is_null(self::$instance)) {
- // self::$instance = new self($engine, $replace);
- // }
- // return self::$instance;
- // }
- public static function instance()
- {
- if (is_null(self::$instance)) {
- self::$instance = new self();
- }
- return self::$instance;
- }
- /**
- * 变量名替换
- * @param $name
- * @param $value
- */
- public function assign($name, $value)
- {
- if (is_array($name)) {
- $this->data = array_merge($this->data, $name);
- } else {
- $this->data[$name] = $value;
- }
- return $this;
- }
- /**
- * 显示视图
- * @param $file
- */
- // public function display($file)
- // {
- // $file = APP.'/views/'.$file;
- // if (is_file($file)){
- // extract($this->assign);#从数组中将变量导入到当前的符号表
- // include $file;
- // }
- // }
- public function fetch($file = "")
- {
- // 页面缓存
- ob_start();
- ob_implicit_flush(0);
- if (!empty($this->data)) {
- extract($this->data);
- }
- if ($file) {
- $namearary = explode(".", $file);
- $typename = end($namearary);
- if (!in_array($typename, ['html', 'tpl', 'htm', 'php'])) {
- $file = $file . '.' . TPL;
- }
- $filename = APP_PATH . "/" . $GLOBALS['model'] . "/view/" . strtolower($GLOBALS['ctrl']) . "/" . $file;
- require($filename);
- } else {
- require(APP_PATH . DS . $GLOBALS['model'] . DS . 'view' . DS . strtolower($GLOBALS['ctrl']) . DS . $GLOBALS['action'] . TPL);
- }
- // 获取并清空缓存
- $content = ob_get_clean();
- return $content;
- }
- }
|