Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php实现mvc模式的例子

php实现mvc模式的例子

WBOY
WBOYasal
2016-07-25 09:05:30946semak imbas
  1. {some_text}

  2. {some_more_text}

复制代码

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

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

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

二、模型(Model)

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

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

三、控制器(controller)

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

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

这段代码混用了面向过程和对象的代码,但是对于小的站点来说,这通常是最好的选择。虽然上边的代码还可以优化。 控制器实际上是用来触发模型的数据和视图元素之间的绑定的控件。

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

  1. /**

  2. * A simple class for querying MySQL
  3. */
  4. class DataAccess {
  5. /**
  6. * Private
  7. * $db stores a database resource
  8. */
  9. var $db;
  10. /**
  11. * Private
  12. * $query stores a query resource
  13. */
  14. var $query; // Query resource
  15. //! A constructor.

  16. /**
  17. * Constucts a new DataAccess object
  18. * @param $host string hostname for dbserver
  19. * @param $user string dbserver user
  20. * @param $pass string dbserver user password
  21. * @param $db string database name
  22. */
  23. function DataAccess ($host,$user,$pass,$db) {
  24. $this->db=mysql_pconnect($host,$user,$pass);
  25. mysql_select_db($db,$this->db);
  26. }
  27. //! An accessor

  28. /**
  29. * Fetches a query resources and stores it in a local member
  30. * @param $sql string the database query to run
  31. * @return void
  32. */
  33. function fetch($sql) {
  34. $this->query=mysql_unbuffered_query($sql,$this->db); // Perform query here
  35. }
  36. //! An accessor

  37. /**
  38. * Returns an associative array of a query row
  39. * @return mixed
  40. */
  41. function getRow () {
  42. if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) )
  43. return $row;
  44. else
  45. return false;
  46. }
  47. }
  48. ?>
复制代码

在它上面放上模型。

  1. /**

  2. * Fetches "products" from the database
  3. * link: http://bbs.it-home.org
  4. */
  5. class ProductModel {
  6. /**
  7. * Private
  8. * $dao an instance of the DataAccess class
  9. */
  10. var $dao;
  11. //! A constructor.

  12. /**
  13. * Constucts a new ProductModel object
  14. * @param $dbobject an instance of the DataAccess class
  15. */
  16. function ProductModel (&$dao) {
  17. $this->dao=& $dao;
  18. }
  19. //! A manipulator

  20. /**
  21. * Tells the $dboject to store this query as a resource
  22. * @param $start the row to start from
  23. * @param $rows the number of rows to fetch
  24. * @return void
  25. */
  26. function listProducts($start=1,$rows=50) {
  27. $this->dao->fetch("SELECT * FROM products LIMIT ".$start.", ".$rows);
  28. }
  29. //! A manipulator

  30. /**
  31. * Tells the $dboject to store this query as a resource
  32. * @param $id a primary key for a row
  33. * @return void
  34. */
  35. function listProduct($id) {
  36. $this->dao->fetch("SELECT * FROM products WHERE PRODUCTID='".$id."'");
  37. }
  38. //! A manipulator

  39. /**
  40. * Fetches a product as an associative array from the $dbobject
  41. * @return mixed
  42. */
  43. function getProduct() {
  44. if ( $product=$this->dao->getRow() )
  45. return $product;
  46. else
  47. return false;
  48. }
  49. }
  50. ?>
复制代码

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

接下来是视图(以下代码去掉了html内容)。

  1. /**

  2. * Binds product data to HTML rendering
  3. * link:http://bbs.it-home.org
  4. */
  5. class ProductView {
  6. /**
  7. * Private
  8. * $model an instance of the ProductModel class
  9. */
  10. var $model;
  11. /**

  12. * Private
  13. * $output rendered HTML is stored here for display
  14. */
  15. var $output;
  16. //! A constructor.

  17. /**
  18. * Constucts a new ProductView object
  19. * @param $model an instance of the ProductModel class
  20. */
  21. function ProductView (&$model) {
  22. $this->model=& $model;
  23. }
  24. //! A manipulator

  25. /**
  26. * Builds the top of an HTML page
  27. * @return void
  28. */
  29. function header () {
  30. }

  31. //! A manipulator

  32. /**
  33. * Builds the bottom of an HTML page
  34. * @return void
  35. */
  36. function footer () {
  37. }

  38. //! A manipulator

  39. /**
  40. * Displays a single product
  41. * @return void
  42. */
  43. function productItem($id=1) {
  44. $this->model->listProduct($id);
  45. while ( $product=$this->model->getProduct() ) {
  46. // Bind data to HTML
  47. }
  48. }
  49. //! A manipulator

  50. /**
  51. * Builds a product table
  52. * @return void
  53. */
  54. function productTable($rownum=1) {
  55. $rowsperpage='20';
  56. $this->model->listProducts($rownum,$rowsperpage);
  57. while ( $product=$this->model->getProduct() ) {
  58. // Bind data to HTML
  59. }
  60. }
  61. //! An accessor

  62. /**
  63. * Returns the rendered HTML
  64. * @return string
  65. */
  66. function display () {
  67. return $this->output;
  68. }
  69. }
  70. ?>
复制代码

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

  1. /**

  2. * Controls the application
  3. */
  4. class ProductController extends ProductView {
  5. //! A constructor.

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

注意:这不是实现MVC的唯一方式——比如你可以用控制器实现模型同时整合视图。这只是演示模式的一种方法。 index.php 文件看起来像这样:

  1. require_once('lib/DataAccess.php');

  2. require_once('lib/ProductModel.php');
  3. require_once('lib/ProductView.php');
  4. require_once('lib/ProductController.php');
  5. $dao=& new DataAccess ('localhost','user','pass','dbname');

  6. $productModel=& new ProductModel($dao);
  7. $productController=& new ProductController($productModel,$_GET);
  8. echo $productController->display();
  9. ?>
复制代码

有一些使用控制器的技巧,在PHP中你可以这样做: $this->{$_GET['method']}($_GET['param']); 建议最好定义程序URL的名字空间形式(namespace),那样它会比较规范比如:

  1. "index.php?class=ProductView&method=productItem&id=4"
复制代码

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

  1. $view=new $_GET['class'];
  2. $view->{$_GET['method']($_GET['id']);
复制代码

有时建立控制器并非易事,比如需要在开发速度和适应性之间权衡时。 一个获得灵感的好去处是Apache group 的Java Struts,它的控制器完全是由XML文档定义的。



Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn