Php 如何在没有框架的情况下实现类似MVC视图的模式

Php 如何在没有框架的情况下实现类似MVC视图的模式,php,codeigniter,Php,Codeigniter,MVC模式允许您定义视图,然后通过控制器将变量加载到视图中,这非常方便。为了便于讨论,让我们以CodeIgniter为例: 控制器: Class Example extends CI_controller(){ function show_page(){ $data = array('msg'=>'Hello World'); echo $this->load->view('hello',$data

MVC模式允许您定义视图,然后通过控制器将变量加载到视图中,这非常方便。为了便于讨论,让我们以CodeIgniter为例:

控制器:

Class Example extends CI_controller(){
          function show_page(){
               $data = array('msg'=>'Hello World');
               echo $this->load->view('hello',$data);
          }
}
视图(hello.php):

主要内容:



有可能做到这一点吗?有人能给出一个函数示例来说明如何做到这一点吗。谢谢

当然,框架就是这么做的。下面是我希望它如何工作的基本概述:

function view($template, $data){
    extract($data);       // this pulls all of the first-level array keys out as their own separate variables
    ob_start();           // this turns on **output buffering** which is the method we'll use to "capture" the contents of the view (there are surely other ways)
    require $template;    // you should prepend some sort of fixed path to this where all of your templates will reside
    echo ob_get_flush();  // turns off output buffering, returning the buffered content as a string which we then send to the browser.
}

当然是这样,但是现有的框架(比如CI)已经解决了这个问题以及大量的bug和用例。如果你沿着这条路走下去,你只会做那些在这些框架上工作的程序员已经做过的事情。有什么原因不能使用现有的框架吗?明白。事实上,我每天工作时都会摇头,看看这个系统是如何组装起来的。2.0版本肯定会实现一个框架。但在2.0版本实施之前,现有系统至少还有一到两年的预期寿命。此外,还有这样一种客户心态:“如果它没有坏,为什么要修理它?”?只要给它添加新功能就行了。“我能感同身受!这些年来我一直摇头。我仍然从客户那里收到完全相同的请求,并且我同意,使用旧的或拼凑在一起的代码可能会是一种痛苦。然而,如果你自己去创建一个控制器/视图系统,我想你会发现这是一个很滑的斜坡。但我通常只是建议使用现有的框架,比如Symfony。如果你创建了自己的框架,你基本上只是在创建另一个框架。根据您的技能,它可能比现有的更好,但作为一个整体包,包括可扩展性、测试、文档和社区-您没有竞争的机会。视图指南和控制器指南很棒!这对我帮助很大。实际上解决了这个问题,而不是对MVC框架发表意见。这是一个呈现模板的函数,而不是视图。@tereško,明白了。这就是为什么我的回答说“这对我帮助很大”,需要调整它以满足我的需要。谢谢
View_folder
     - hello.php
Class
 - view_class.php`
<?php
 $data['msg'] = 'Hello World!';
 echo $view_class->get_view('hello.php',$data); 
?> 
function view($template, $data){
    extract($data);       // this pulls all of the first-level array keys out as their own separate variables
    ob_start();           // this turns on **output buffering** which is the method we'll use to "capture" the contents of the view (there are surely other ways)
    require $template;    // you should prepend some sort of fixed path to this where all of your templates will reside
    echo ob_get_flush();  // turns off output buffering, returning the buffered content as a string which we then send to the browser.
}