模板处理是用单独的方法来处理还是直接include呢?

浏览:1467 发布日期:2015/03/25 分类:技术分享
一般MVC的view实现都是2种方式
要么是单独类或者或者方法.类似于TP,,,这样的话,如果需要往模板里push变量的话,需要控制器里手动操作,比如TP 的assign 然后在display,,比较麻烦.而且变量会重复定义,比较浪费
还有一种就是直接在控制器里include 这样的话,所有在当前控制器的变量都可以在模板里使用,但是这样的话,就比较混乱..但是操作起来很自由,在模板里可以直接使用$this->xxx 也可以直接使用控制器里的变量

各位觉得哪种方式比较好!

还有就是 模板便签的问题,,到底原生的PHP模板好,还是用标签呢,如果原生的模板里各种<?php ?>大括号小括号,看的眼花缭乱,但是不需要生成模板缓存,速度快!如果用模板便签的话,.模板里面看起来很好看,但是需要生成模板缓存,浪费资源!

附上2种方式的简单实现!

第一种,原生PHP模板 使用单独的方法输出 protected function output($template_file, $data) {
        if (!$this->tempate_path) {
            $this->tempate_path = 'template/design1/';
        }
        $template_file = XITIE_PATH . $this->tempate_path . 'html/' . $template_file . '.php';
        if (is_file($template_file)) {
            extract($data);
            ob_start();
            require $template_file;
            $output = ob_get_contents();
            ob_end_clean();
            $output = $this->compress($output);
            if (!headers_sent()) {
                foreach ($this->headers as $header) {
                    header($header, true);
                }
            }
            echo $output;
        } else {
            exit('模板不存在:' . $template_file);
        }
    }

    private function compress($data, $level = 0) {
        if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)) {
            $encoding = 'gzip';
        }
        if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false)) {
            $encoding = 'x-gzip';
        }
        if (!isset($encoding) || ($level < -1 || $level > 9)) {
            return $data;
        }
        if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
            return $data;
        }
        if (headers_sent()) {
            return $data;
        }
        if (connection_status()) {
            return $data;
        }
        $this->addHeader('Content-Encoding: ' . $encoding);
        return gzencode($data, (int) $level);
    }

    protected function addHeader($header) {
        $this->headers[] = $header;
    }
第二种 直接在控制器里include 模板
控制器里面    public function index() {
        $musics = require XITIE_PATH . 'music.php';
        $templates = require XITIE_PATH . 'template.php';
        $result = model('xitie')->find('uid=' . $this->user_info['id']);
        if ($result) {
            extract($result);
            $template_info = $templates[$template];
            $music_info = $musics[$music];
            $wedding_list = string2array($wedding_list);
        }

        include template('create');
    }
template 函数/**
 * 模板函数
 * @param string $template 模板文件名
 * @param string $path  模板路径
 * @param string $suffix 模板后缀
 */
function template($template = '', $path = '', $suffix = '', $show_error = true) {
    $tpl_path = $path ? $path : (config('tpl_path') ? config('tpl_path') : './template/');
    $tpl_suffix = $suffix ? $suffix : (config('tpl_suffix') ? config('tpl_suffix') : '.html');
    if (empty($template)) {
        $template_file = $tpl_path . __MODULE__ . '/' . __CONTROLLER__ . '/' . __ACTION__;
    } else {
        if (!$path) {
            $pcount = substr_count($template, '/');
            if ($pcount == 0) {
                $template_file = $tpl_path . __MODULE__ . '/' . __CONTROLLER__ . '/' . trim($template, '/');
            } else if ($pcount == 1) {
                $template_file = $tpl_path . __MODULE__ . '/' . trim($template, '/');
            } else {
                $template_file = $tpl_path . trim($template, '/');
            }
        } else {
            $template_file = $path . trim($template, '/');
        }
    }
    $template_file .= $tpl_suffix;
    if (!is_file($template_file)) {
        if ($show_error === true) {
            halt('模板文件不存在:' . $template_file);
        }
    } else {
        $cache_template = DATA_PATH . 'cache' . _DIR . 'template' . _DIR . __MODULE__ . _DIR . md5($template_file) . '.php';
        if (is_file($cache_template) && config('tpl_cache') == true && (config('tpl_expire') == 0 || (@filemtime($cache_template) + config('tpl_expire')) < time())) {
            
        } else {
            template::template_compile($template_file, $cache_template);
        }
        return $cache_template;
    }
}

function template_exists($template = '', $path = '', $suffix = '') {
    $tpl_path = $path ? $path : (config('tpl_path') ? config('tpl_path') : './template/');
    $tpl_suffix = $suffix ? $suffix : (config('tpl_suffix') ? config('tpl_suffix') : '.html');
    if (empty($template)) {
        $template_file = $tpl_path . __MODULE__ . '/' . __CONTROLLER__ . '/' . __ACTION__;
    } else {
        if (!$path) {
            $pcount = substr_count($template, '/');
            if ($pcount == 0) {
                $template_file = $tpl_path . __MODULE__ . '/' . __CONTROLLER__ . '/' . trim($template, '/');
            } else if ($pcount == 1) {
                $template_file = $tpl_path . __MODULE__ . '/' . trim($template, '/');
            } else {
                $template_file = $tpl_path . trim($template, '/');
            }
        } else {
            $template_file = $path . trim($template, '/');
        }
    }
    $template_file .= $tpl_suffix;
    return is_file($template_file);
}
template编译类class template {

    /**
     * 编译模板
     * @param string  $template_file 模板文件
     * @param string $cache_file 缓存文件
     */
    public static function template_compile($template_file, $cache_file) {
        if (!is_file($template_file)) {
            return false;
        }
        $content = file_get_contents($template_file);
        $cache_dir = dirname($cache_file);
        if (!is_dir($cache_dir)) {
            mkdir($cache_dir, 0777, true);
        }
        $content = self::parse_template($content);
        @file_put_contents($cache_file, $content);
        return $cache_file;
    }

    public static function parse_template($str) {
        //{literal}
        $str = preg_replace('/\{literal\}([\d\D]+?)\{\/literal\}/ie', "self::literal('$1',1)", $str);
        
        //include
        $str = preg_replace("/\{template\s+(.+)\}/", "<?php include template(\\1,'','','',false); ?>", $str);
        $str = preg_replace("/\{include\s+(.+)\}/", "<?php include \\1; ?>", $str);        
        
        $str = preg_replace("/\{php\s+(.+?)\}/", "<?php \\1?>", $str);
        $str = preg_replace("/\{!(.+?)\}/", "<?php \\1?>", $str);
        $str = preg_replace("/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str);
        $str = preg_replace("/\{else\}/", "<?php } else { ?> ", $str);
        $str = preg_replace("/\{elseif\s+(.+?)\}/", "<?php } elseif (\\1) { ?> ", $str);
        $str = preg_replace("/\{\/if\}/", "<?php } ?>", $str);
        //for
        $str = preg_replace("/\{for\s+(.+?)\}/", "<?php for(\\1) { ?>", $str);
        $str = preg_replace("/\{\/for\}/", "<?php } ?>", $str);
        //++ --         
        $str = preg_replace("/\{\+\+(.+?)\}/", "<?php ++\\1; ?>", $str);
        $str = preg_replace("/\{\-\-(.+?)\}/", "<?php ++\\1; ?>", $str);
        $str = preg_replace("/\{(.+?)\+\+\}/", "<?php \\1++; ?>", $str);
        $str = preg_replace("/\{(.+?)\-\-\}/", "<?php \\1--; ?>", $str);
        //loop
        $str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\}/", "<?php \$n=1;if(is_array(\\1)) foreach(\\1 AS \\2) { ?>", $str);
        $str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php \$n=1; if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>", $str);
        $str = preg_replace("/\{\/loop\}/", "<?php \$n++;}unset(\$n); ?>", $str);
        //函数
        $str = preg_replace("/\{:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{~([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php \\1;?>", $str);
        //变量
        
        $str = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\->[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:])\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|([^{}]*)\}/", "<?php if(!empty(\\1)){echo \\1;}else{echo \\2;}?>", $str);
        $str = preg_replace('/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\->)[^\}]+)\}/',"<?php echo \\1;?>", $str);
        
        //数组
        $str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "self::addquote('<?php echo \\1;?>')", $str);
        $str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\|([^{}]*)\}/es", "self::addquote('<?php if(!empty(\\1)){echo \\1;}else{echo \\2;} ?>')", $str);

        //常量
        $str = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str);
        //扩展标签
        $str = preg_replace("/\{tag:(\w+)\s+([^}]+)\}/ie", "self::tag('$1','$2')", $str);
        $str = preg_replace("/\{:tag:(\w+)\s+([^}]+)\}/ie", "self::tag('$1','$2',true)", $str);
        $str = preg_replace('/\{literal\}([\d\D]+?)\{\/literal\}/ie', "self::literal('$1',0)", $str);
        return $str;
    }
    
    public static function literal($str,$type = 1){
        $str = stripslashes($str);
        if($type == 1){
            $str = preg_replace(array( 
                '/\{/','/\}/'            
            ), array( 
                '[{]','[}]'            
            ), $str);
            $str = '{literal}'.$str.'{/literal}';
        }else{ 
           $str = preg_replace(array( 
                '/\[\{\]/','/\[\}\]/'            
            ), array( 
                '{','}'            
            ), $str);             
        }
        return $str;
    }

    public static function addquote($var) {
        return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
    }

    public static function tag($name, $data, $echo = false) {
        preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);

        foreach ($matches as $v) {
            if (in_array($v[1], array('action', 'cache', 'return'))) {
                $$v[1] = $v[2];
                continue;
            }

            $datas[$v[1]] = $v[2];
        }
        if (!isset($action) || empty($action)) { //方法
            return false;
        }
        if (isset($cache)) { //缓存
            $cache = intval($cache);
        } else {
            $cache = false;
        }
        if (!isset($return) || empty($return)) {
            $return = '$data';
        }
        $tag_file = EXT_PATH . 'tags' . _DIR . $name . '_tag' . EXT;
        if (!is_file($tag_file)) {
            return false;
        }
        $str = '<?php ';
        if ($cache !== false) {
            $cache_name =  'tag/'.$name.'_'.$action.  to_guid_string($datas);
            $str .= '$cache = cache::getInstance();';
            $str .= $return . '=$cache->get("' . $cache_name . '");';
            $str .= 'if(' . $return . ' === false){';
            $str .= '$params = ' . self::filter_var($datas) . ';';
            $str .= '$tag = load_ext("tags/' . $name . '_tag",true);';
            $str .= $return . '=$tag->' . $action . '($params);';
            $str .= '$cache->set("' . $cache_name . '",' . $return . ',' . $cache . ');';
            $str .= '}';
            if ($echo == true) {
                $str .= 'echo ' . $return . ';';
            }
            $str .= ' ?>';
        } else {

            $str .= '$params = ' . self::filter_var($datas) . ';';
            $str .= '$tag = load_ext("tags/' . $name . '_tag",true);';
            if ($echo) {
                $str .= 'echo $tag->' . $action . '($params);';
            } else {
                $str .= $return . '=$tag->' . $action . '($params);';
            }
            $str .= ' ?>';
        }
        return $str;
    }

    protected static function filter_var($data) {
        $str = var_export($data, true);
        //$str = preg_replace('/\'\$(\w+?)\'/', "\$\\1", $str);
        $str = preg_replace('/\'/', '"', $str);
        $str = preg_replace('/\s{2,}/', '', $str);
        return $str;
    }

}
最佳答案
评论( 相关
后面还有条评论,点击查看>>