Home  >  Article  >  Backend Development  >  Example of php implementing mvc mode

Example of php implementing mvc mode

WBOY
WBOYOriginal
2016-07-25 09:05:30996browse
  1. {some_text}

  2. {some_more_text}

Copy code

They have no meaning in the documentation, all they mean is PHP will replace it with something else.

If you agree with this loose description of views, you will also agree that most template solutions do not effectively separate views and models. The template tag will be replaced with whatever is stored in the model.

Ask yourself a few questions when you implement the view: "Is it easy to replace the entire view?" "How long does it take to implement a new view?" "Is it easy to replace the view's description language? (For example, using SOAP document replaces HTML document)"

2. Model

Model represents program logic. (Often called the business layer in enterprise-level programs)

In general, the task of the model is to convert the original data into data containing certain meanings, which will be displayed by the view. Typically, the model will encapsulate data queries, perhaps through some abstract data class (data access layer) to implement the query. For example, if you wish to calculate the annual rainfall in the UK (just to find yourself a nice holiday spot), the model will receive the daily rainfall for ten years, calculate the average, and pass it to the view.

3. Controller

Simply put, the controller is the first part called by the incoming HTTP request in the web application. It checks the received request, such as some GET variables, and makes appropriate feedback. It's difficult to start writing other PHP code until you write your first controller. The most common usage is a structure like 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-oriented and Object's code, but for small sites this is usually the best option. Although the above code can still be optimized. Controllers are actually controls used to trigger bindings between the model's data and view elements.

Here is a simple example using MVC pattern. First we need a database access class, which is an ordinary 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. < p>//! 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, their interaction is never more than one line - no multiple lines are sent, which can quickly slow down the program. For the same program that uses schema classes, it only needs to keep one row (Row) in memory - the rest is given to the saved query resource (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. < p>/**
  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. < ;p>}

  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. A constructor.

/**
* Controls the application
*/
    function ProductController (&$model,$getvars=null) {
  1. ProductView::ProductView($model);
  2. $this->header();
  3. switch ( $getvars['view'] ) {
  4. case "product":
  5. $this->productItem($getvars['id']);
  6. break;
  7. default:
  8. if ( empty ($getvars['rownum']) ) {
  9. $this-> ;productTable();
  10. } else {
  11. $this->productTable($getvars['rownum']);
  12. }
  13. break;
  14. }
  15. $this->footer();
  16. }
  17. }
  18. ?> ;
  19. Copy code
  20. Note: This is not the only way to implement MVC - for example, you can use controllers to implement models and integrate views at the same time. This is just one way to demonstrate the pattern. The index.php file looks like this:
  21. 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();
?>

  1. Copy code
  2. There are some tricks for using controllers, in PHP you can do this: $this->{$_GET['method']}($_GET['param']); It is recommended to define the namespace form of the program URL, so that it will be more standardized, such as:
  3. "index.php?class=ProductView&method=productItem&id=4"
Copy the code
It can handle the controller like this:

    $view=new $_GET['class'];
  1. $view->{$_GET['method']($_GET['id']);
Copy code

Sometimes building a controller is not an easy task, such as when there is a trade-off between development speed and adaptability. A good place to get inspiration is the Apache group's Java Struts, whose controllers are entirely defined by XML documents.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn