控制器(controllerQ?/strong>
单的说控制器是Web应用中进入的HTTPh最先调用的一部分。它查收到的hQ比如一些GET变量Q做出合适的反馈。在写出你的W一个控制器之前Q你很难开始编写其他的PHP代码。最常见的用法是index.php中像switch语句的结构:
<?php
switch ($_GET['viewpage']) {
case "news":
$page=new NewsRenderer;
break;
case "links":
$page=new LinksRenderer;
break;
default:
$page=new HomePageRenderer;
break;
}
$page->display();
?>
q段代码L了面向过E和对象的代码,但是对于的站点来说Q这通常是最好的选择。虽然上边的代码q可以优化?br />
控制器实际上是用来触发模型的数据和视囑օ素之间的l定的控件?br />
例子
q里是一个用MVC模式的简单例子?br />
首先我们需要一个数据库讉Kc,它是一个普通类?br />
<?php
/**
* A simple class for querying MySQL
*/
class DataAccess {
/**
* Private
* $db stores a database resource
*/
var $db;
/**
* Private
* $query stores a query resource
*/
var $query; // Query resource
//! A constructor.
/**
* Constucts a new DataAccess object
* @param $host string hostname for dbserver
* @param $user string dbserver user
* @param $pass string dbserver user password
* @param $db string database name
*/
function DataAccess ($host,$user,$pass,$db) {
$this->db=mysql_pconnect($host,$user,$pass);
mysql_select_db($db,$this->db);
}
//! An accessor
/**
* Fetches a query resources and stores it in a local member
* @param $sql string the database query to run
* @return void
*/
function fetch($sql) {
$this->query=mysql_unbuffered_query($sql,$this->db); // Perform query here
}
//! An accessor
/**
* Returns an associative array of a query row
* @return mixed
*/
function getRow () {
if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) )
return $row;
else
return false;
}
}
?>
在它上边放上模型?br />
<?php
/**
* Fetches "products" from the database
*/
class ProductModel {
/**
* Private
* $dao an instance of the DataAccess class
*/
var $dao;
//! A constructor.
/**
* Constucts a new ProductModel object
* @param $dbobject an instance of the DataAccess class
*/
function ProductModel (&$dao) {
$this->dao=& $dao;
}
//! A manipulator
/**
* Tells the $dboject to store this query as a resource
* @param $start the row to start from
* @param $rows the number of rows to fetch
* @return void
*/
function listProducts($start=1,$rows=50) {
$this->dao->fetch("SELECT * FROM products LIMIT ".$start.", ".$rows);
}
//! A manipulator
/**
* Tells the $dboject to store this query as a resource
* @param $id a primary key for a row
* @return void
*/
function listProduct($id) {
$this->dao->fetch("SELECT * FROM products WHERE PRODUCTID='".$id."'");
}
//! A manipulator
/**
* Fetches a product as an associative array from the $dbobject
* @return mixed
*/
function getProduct() {
if ( $product=$this->dao->getRow() )
return $product;
else
return false;
}
}
?>
有一点要注意的是Q在模型和数据访问类之间Q它们的交互从不会多于一??没有多行被传送,那样会很快ɽE式慢下来。同LE式对于使用模式的类Q它只需要在内存中保留一行(RowQ??其他的交l已保存的查询资源(query resourceQ??换句话说Q我们让MYSQL替我们保持结果?br />
接下来是视图??我去掉了HTML以节省空_你可以查看这文章的完整代码?br />
<?php
/**
* Binds product data to HTML rendering
*/
class ProductView {
/**
* Private
* $model an instance of the ProductModel class
*/
var $model;
/**
* Private
* $output rendered HTML is stored here for display
*/
var $output;
//! A constructor.
/**
* Constucts a new ProductView object
* @param $model an instance of the ProductModel class
*/
function ProductView (&$model) {
$this->model=& $model;
}
//! A manipulator
/**
* Builds the top of an HTML page
* @return void
*/
function header () {
}
//! A manipulator
/**
* Builds the bottom of an HTML page
* @return void
*/
function footer () {
}
//! A manipulator
/**
* Displays a single product
* @return void
*/
function productItem($id=1) {
$this->model->listProduct($id);
while ( $product=$this->model->getProduct() ) {
// Bind data to HTML
}
}
//! A manipulator
/**
* Builds a product table
* @return void
*/
function productTable($rownum=1) {
$rowsperpage='20';
$this->model->listProducts($rownum,$rowsperpage);
while ( $product=$this->model->getProduct() ) {
// Bind data to HTML
}
}
//! An accessor
/**
* Returns the rendered HTML
* @return string
*/
function display () {
return $this->output;
}
}
?>
最后是控制器,我们把视图实现Z个子cR?br />
<?php
/**
* Controls the application
*/
class ProductController extends ProductView {
//! A constructor.
/**
* Constucts a new ProductController object
* @param $model an instance of the ProductModel class
* @param $getvars the incoming HTTP GET method variables
*/
function ProductController (&$model,$getvars=null) {
ProductView::ProductView($model);
$this->header();
switch ( $getvars['view'] ) {
case "product":
$this->productItem($getvars['id']);
break;
default:
if ( empty ($getvars['rownum']) ) {
$this->productTable();
} else {
$this->productTable($getvars['rownum']);
}
break;
}
$this->footer();
}
}
?>

注意q不是实现MVC的唯一方式??比如你可以用控制器实现模型同时整合视图。这只是演示模式的一U方法?br />
我们的index.php 文g看v来像q样Q?br />
<?php
require_once('lib/DataAccess.php');
require_once('lib/ProductModel.php');
require_once('lib/ProductView.php');
require_once('lib/ProductController.php');
$dao=& new DataAccess ('localhost','user','pass','dbname');
$productModel=& new ProductModel($dao);
$productController=& new ProductController($productModel,$_GET);
echo $productController->display();
?>
漂亮而简单?br />
我们有一些用控制器的技巧,在PHP中你可以q样做:
$this->{$_GET['method']}($_GET['param']);
一个徏议是你最好定义程序URL的名字空间Ş式(namespaceQ,那样它会比较规范比如Q?br />
"index.php?class=ProductView&method=productItem&id=4"
通过它我们可以这样处理我们的控制器:
$view=new $_GET['class'];
$view->{$_GET['method']($_GET['id']);
有时候,建立控制器是件很困难的事情,比如当你在开发速度和适应性之间权衡时。一个获得灵感的好去处是Apache group 的Java StrutsQ它的控制器完全是由XML文定义的?
相关附gQ?/strong>本文完整实例
本文英文原版地址Q?/strong>http://www.phppatterns.com/index.php/article/articleview/11/

]]>