MVC模式的PHP实现

作者:Harry Fuecks 翻译:Easy Chen
MVC模式在网站架构中十分常见。它允许我们建立一个三层结构的应用程式,从代码中分离出有用的层,帮助设计师和开发者协同工作以及提高我们维护和扩展既有程式的能力。

视图(View)

“视图”主要指我们送到Web浏览器的最终结果——比如我们的脚本生成的HTML。当说到视图时,很多人想到的是模版,但是把模板方案叫做视图的正确性是值得怀疑的。

对视图来说,最重要的事情可能是它应该是“自我意识(self aware)”的,视图被渲染(render)时,视图的元素能意识到自己在更大框架中的角色。

以XML为例,可以说XML在被解析时,DOM API有着这样的认知——一个DOM树里的节点知道它在哪里和它包含了什么。 (当一个XML文档中的节点用SAX解析时只有当解析到该节点时它才有意义。)

绝大多数模板方案使用简单的过程语言和这样的模板标签:

1<p>{some_text}</p>
1<p>{some_more_text}</p>

它们在文档中没有意义,它们代表的意义只是PHP将用其他的东西来替换它。

如果你同意这种对视图的松散描述,你也就会同意绝大多数模板方案并没有有效的分离视图和模型。模板标签将被替换成什么存放在模型中。

在你实现视图时问自己几个问题:“全体视图的替换容易吗?”“实现一个新视图要多久?” “能很容易的替换视图的描述语言吗?(比如在同一个视图中用SOAP文档替换HTML文档)”

模型(Model)

模型代表了程序逻辑。(在企业级程序中经常称为业务层(business layer))

总的来说,模型的任务是把原有数据转换成包含某些意义的数据,这些数据将被视图所显示。通常,模型将封装数据查询,可能通过一些抽象数据类(数据访问层)来实现查询。举例说,你希望计算英国年度降雨量(只是为了给你自己找个好点的度假地),模型将接收十年中每天的降雨量,计算出平均值,再传递给视图。

控制器(controller)

简单的说控制器是Web应用中进入的HTTP请求最先调用的一部分。它检查收到的请求,比如一些GET变量,做出合适的反馈。在写出你的第一个控制器之前,你很难开始编写其他的PHP代码。最常见的用法是index.php中像switch语句的结构:

 1   
 2switch ($_GET['viewpage']) {   
 3case "news":   
 4$page=new NewsRenderer;   
 5break;   
 6case "links":   
 7$page=new LinksRenderer;   
 8break;   
 9default:   
10$page=new HomePageRenderer;   
11break;   
12}   
13$page->display();   

这段代码混用了面向过程和对象的代码,但是对于小的站点来说,这通常是最好的选择。虽然上边的代码还可以优化。

控制器实际上是用来触发模型的数据和视图元素之间的绑定的控件。

例子

这里是一个使用MVC模式的简单例子。
首先我们需要一个数据库访问类,它是一个普通类。

 1   
 2/**   
 3* A simple class for querying MySQL   
 4*/   
 5class DataAccess {   
 6/**   
 7* Private   
 8* $db stores a database resource   
 9*/   
10var $db;   
11/**   
12* Private   
13* $query stores a query resource   
14*/   
15var $query; // Query resource 
16
17//! A constructor.   
18/**   
19* Constucts a new DataAccess object   
20* @param $host string hostname for dbserver   
21* @param $user string dbserver user   
22* @param $pass string dbserver user password   
23* @param $db string database name   
24*/   
25function DataAccess ($host,$user,$pass,$db) {   
26$this->db=mysql_pconnect($host,$user,$pass);   
27mysql_select_db($db,$this->db);   
28} 
29
30//! An accessor   
31/**   
32* Fetches a query resources and stores it in a local member   
33* @param $sql string the database query to run   
34* @return void   
35*/   
36function fetch($sql) {   
37$this->query=mysql_unbuffered_query($sql,$this->db); // Perform query here   
38} 
39
40//! An accessor   
41/**   
42* Returns an associative array of a query row   
43* @return mixed   
44*/   
45function getRow () {   
46if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) )   
47return $row;   
48else   
49return false;   
50}   
51}   

在它上边放上模型。

 1   
 2/**   
 3* Fetches "products" from the database   
 4*/   
 5class ProductModel {   
 6/**   
 7* Private   
 8* $dao an instance of the DataAccess class   
 9*/   
10var $dao; 
11
12//! A constructor.   
13/**   
14* Constucts a new ProductModel object   
15* @param $dbobject an instance of the DataAccess class   
16*/   
17function ProductModel (&$dao) {   
18$this->dao=& $dao;   
19} 
20
21//! A manipulator   
22/**   
23* Tells the $dboject to store this query as a resource   
24* @param $start the row to start from   
25* @param $rows the number of rows to fetch   
26* @return void   
27*/   
28function listProducts($start=1,$rows=50) {   
29$this->dao->fetch("SELECT * FROM products LIMIT ".$start.", ".$rows);   
30} 
31
32//! A manipulator   
33/**   
34* Tells the $dboject to store this query as a resource   
35* @param $id a primary key for a row   
36* @return void   
37*/   
38function listProduct($id) {   
39$this->dao->fetch("SELECT * FROM products WHERE PRODUCTID='".$id."'");   
40} 
41
42//! A manipulator   
43/**   
44* Fetches a product as an associative array from the $dbobject   
45* @return mixed   
46*/   
47function getProduct() {   
48if ( $product=$this->dao->getRow() )   
49return $product;   
50else   
51return false;   
52}   
53}   

有一点要注意的是,在模型和数据访问类之间,它们的交互从不会多于一行——没有多行被传送,那样会很快使程式慢下来。同样的程式对于使用模式的类,它只需要在内存中保留一行(Row)——其他的交给已保存的查询资源(query resource)——换句话说,我们让MYSQL替我们保持结果。

接下来是视图——我去掉了HTML以节省空间,你可以查看这篇文章的完整代码。

 1   
 2/**   
 3* Binds product data to HTML rendering   
 4*/   
 5class ProductView {   
 6/**   
 7* Private   
 8* $model an instance of the ProductModel class   
 9*/   
10var $model; 
11
12/**   
13* Private   
14* $output rendered HTML is stored here for display   
15*/   
16var $output; 
17
18//! A constructor.   
19/**   
20* Constucts a new ProductView object   
21* @param $model an instance of the ProductModel class   
22*/   
23function ProductView (&$model) {   
24$this->model=& $model;   
25} 
26
27//! A manipulator   
28/**   
29* Builds the top of an HTML page   
30* @return void   
31*/   
32function header () { 
33
34} 
35
36//! A manipulator   
37/**   
38* Builds the bottom of an HTML page   
39* @return void   
40*/   
41function footer () { 
42
43} 
44
45//! A manipulator   
46/**   
47* Displays a single product   
48* @return void   
49*/   
50function productItem($id=1) {   
51$this->model->listProduct($id);   
52while ( $product=$this->model->getProduct() ) {   
53// Bind data to HTML   
54}   
55} 
56
57//! A manipulator   
58/**   
59* Builds a product table   
60* @return void   
61*/   
62function productTable($rownum=1) {   
63$rowsperpage='20';   
64$this->model->listProducts($rownum,$rowsperpage);   
65while ( $product=$this->model->getProduct() ) {   
66// Bind data to HTML   
67}   
68} 
69
70//! An accessor   
71/**   
72* Returns the rendered HTML   
73* @return string   
74*/   
75function display () {   
76return $this->output;   
77}   
78}   

最后是控制器,我们将把视图实现为一个子类。

 1   
 2/**   
 3* Controls the application   
 4*/   
 5class ProductController extends ProductView { 
 6
 7//! A constructor.   
 8/**   
 9* Constucts a new ProductController object   
10* @param $model an instance of the ProductModel class   
11* @param $getvars the incoming HTTP GET method variables   
12*/   
13function ProductController (&$model,$getvars=null) {   
14ProductView::ProductView($model);   
15$this->header();   
16switch ( $getvars['view'] ) {   
17case "product":   
18$this->productItem($getvars['id']);   
19break;   
20default:   
21if ( empty ($getvars['rownum']) ) {   
22$this->productTable();   
23} else {   
24$this->productTable($getvars['rownum']);   
25}   
26break;   
27}   
28$this->footer();   
29}   
30}   

注意这不是实现MVC的唯一方式——比如你可以用控制器实现模型同时整合视图。这只是演示模式的一种方法。

我们的index.php 文件看起来像这样:

 1   
 2require_once('lib/DataAccess.php');   
 3require_once('lib/ProductModel.php');   
 4require_once('lib/ProductView.php');   
 5require_once('lib/ProductController.php'); 
 6
 7$dao=& new DataAccess ('localhost','user','pass','dbname');   
 8$productModel=& new ProductModel($dao);   
 9$productController=& new ProductController($productModel,$_GET);   
10echo $productController->display();   

漂亮而简单。

我们有一些使用控制器的技巧,在PHP中你可以这样做:

$this->{$_GET['method']}($_GET['param']);

一个建议是你最好定义程序URL的名字空间形式(namespace),那样它会比较规范比如:

"index.php?class=ProductView&method=productItem&id=4"

通过它我们可以这样处理我们的控制器:

$view=new $_GET['class'];
$view->{$_GET'method';

有时候,建立控制器是件很困难的事情,比如当你在开发速度和适应性之间权衡时。一个获得灵感的好去处是Apache group 的Java Struts,它的控制器完全是由XML文档定义的。

Published At
Categories with Web编程
Tagged with
comments powered by Disqus