PHP头条
热点:

PHP框架三(视图)


这个视图文件非常简单。主要利用的就是ob_start() ,ob_get_content();这个文件位于includes文件夹内

view.php

[php] 
<?php 
class view{ 
    //视图类型 default / wap 
    public static $view_type = null; 
     
    public function __construct(){ 
        ob_start(); 
    } 
     
    public function finish(){ 
        $content = ob_get_contents(); 
        return $content; 
    } 
     
    public static function set_view_type(){ 
        switch(true){ 
            case stripos($_SERVER['HTTP_USER_AGENT'], 'Windows CE') !== FALSE : self::$view_type = 'wap'; break; 
            default : self::$view_type = 'default'; 
        } 
    } 
     
    public static function show($location , $param = array()){ 
        if(is_null(self::$view_type)){ 
            self::set_view_type(); 
        } 
         
        $view = SIMPLE_PATH . '/view/' . self::$view_type . '/' . $location; 
         
        extract($param, EXTR_OVERWRITE); 
        ob_start(); 
        file_exists($view) ? require $view : exit($view . ' 不存在'); 
        $content = ob_get_contents(); 
        return $content; 
    } 

对于OB函数,我们可以简单地认为,在PHP编译之后,它不会立刻返回到页面,而是先放到缓冲区。

上述视图只是做了一个简单的实现,如果我们要扩展它,可以完善set_view_type()方法,也可以增加缓存,还可以增加模板的支持。

具体实现我会在以后的章节加上,今天我们试着使用一下这个VIEW。

还是昨天controller文件夹下的index.php 文件

[php] 
<?php 
class index{ 
     
    public function demo(){ 
        view::show('index.htm' ,  array('message' => 'HELLO WORLD')); 
    } 

然后再在view文件夹内新建一个default文件夹,再在新建一个index.htm

[html] 
<html> 
<head> 
<title></title> 
</head> 
<body> 
    <?php  
    echo $message; 
?> 
</body> 
</html> 
我们运行站点,便可以看到结果,“HELLO WORLD”。

我觉得这个结果,便是每个程序员对新的思想的一种见证。www.2cto.com

如果在这个文件中,你还想插入头部,或尾部,只要再新建一个head.htm。然后再在index.htm中加入

[html] 
<html> 
<head> 
<title></title> 
</head> 
<body> 
    <?php  
    echo $message; 
    view::show('head.htm'); 
?> 
</body> 
</html> 
就可以实现公共部分的加入了。

至此,我们这个小型的视图类就实现了。

大家可自行去实验,如果不行,我们再交流。

 作者:tomyjohn

www.phpzy.comtrue/phprm/15216.htmlTechArticlePHP框架三(视图) 这个视图文件非常简单。主要利用的就是ob_start() ,ob_get_content();这个文件位于includes文件夹内 view.php [php] ?php class view{ //视图类型 default / wap public static $view_type = null;...

相关文章

    暂无相关文章
相关频道:

PHP之友评论

今天推荐