MVC模式允许您定义视图a,然后通过控制器将变量加载到其中,这真的很方便。为了便于讨论,让我们以CodeIgniter为例:
控制器:
Class Example extends CI_controller(){
function show_page(){
$data = array('msg'=>'Hello World');
echo $this->load->view('hello',$data);
}
}
视图(hello.php):
<h1><?php echo $msg; ?></h1>
我接手了一个几年前写的旧项目,那里到处都是多余的html代码。它没有任何模式,只是简单的、结构糟糕的代码。
我想创建一个类,它有一个函数,可以从一个文件夹中的文件中提取所有HTML代码,向它们提供变量并显示结果。像这样:
文件夹结构:
View_folder
- hello.php
Class
- view_class.php`
Main:
<?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.
}