PHP Implementation of MVC pattern example

Source: Internet
Author: User
    1. {Some_text}

    2. {Some_more_text}

Copy Code

They don't make sense in the document, they mean just that PHP will replace it with something else.

If you agree with this loosely described view, you will agree that the vast majority of template schemes do not effectively separate views and models. The template label will be replaced with what is stored in the model.

Ask yourself a few questions when you implement the view: "Is it easy to replace the whole view?" "" How long does it take to implement a new view? "Can you easily replace the description language of the view?" (such as replacing an HTML document with a SOAP document in the same view) "

Second, model

The model represents the program logic. (often referred to as the business layer in an enterprise-level program)

In general, the task of the model is to convert the original data into data that contains some meaning that will be displayed by the view. Typically, the model encapsulates the data query, possibly through some abstract data classes (the data access layer). For example, if you want to calculate the annual rainfall in the UK (just to find a better place for yourself), the model will receive a daily rainfall of ten years, calculate the average, and pass it on to the view.

III. Controllers (Controller)

Simply put, the controller is part of the first call to the HTTP request that is entered in the Web application. It checks the received requests, such as some get variables, to make the appropriate feedback. Before you write out your first controller, it's hard to start writing other PHP code. The most common usage is the structure of a switch statement in index.php:

    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. ?>
Copy Code

This code mixes process-and object-oriented code, but this is usually the best choice for small sites. Although the above code can also be optimized. A controller is actually a control that is used to trigger a binding between a model's data and a view element.

Here is a simple example of using the MVC pattern. First we need a database access class, which is a generic class.

  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. ?>

Copy Code

Put the model on top of it.

  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. ?>
Copy Code

Note: Between the model and the data access class, they never have more than one line of interaction--no more than one line is passed, which slows the program down very quickly. The same program for a class that uses patterns, it just needs to keep one row in memory (row)--the other to the saved query resource--in other words, we let MySQL keep the results for us.

Next is the view (the following code removes the HTML content).

  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. ?>
Copy Code

Finally, the controller, we will implement the view as a subclass.

  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::P Roductview ($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. ?>
Copy Code

Note: This is not the only way to implement MVC-for example, you can integrate the view with the controller implementation model. This is just one way to demonstrate the pattern. The index.php file looks like this:

    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. ?>

Copy Code

There are some techniques for using the controller, which you can do in PHP: $this->{$_get[' method '} ($_get[' param ')); It is recommended that you define the namespace form (namespace) of the program URL so that it compares specifications such as:

    1. "Index.php?class=productview&method=productitem&id=4"
Copy Code

Through it you can handle the controller:

    1. $view =new $_get[' class ');
    2. $view->{$_get[' method '] ($_get[' id ');
Copy Code

Sometimes it's not easy to build a controller, such as when it comes to balancing development speed and adaptability. A good place to get inspired is the Java Struts of the Apache group, whose controllers are completely defined by the XML document.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.