Example of mvc mode implementation in php

Source: Internet
Author: User
Example of mvc mode implementation in php

  1. {Some_text}

  2. {Some_more_text}

They do not make sense in the document. they represent that PHP will replace it with something else.

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

When you implement a View, ask yourself a few questions: "Is it easy to replace all views ?" "How long does it take to implement a new view ?" "Is it easy to replace the description language of the view? (For example, replacing HTML documents with SOAP documents in the same view )"

II. Model)

The model represents the program logic. (Business layer is often called in enterprise applications ))

In general, the model task is to convert the original data into data that contains some meaning, and the data will be displayed by the view. Generally, the model encapsulates data queries and may use abstract data classes (data access layer) to perform queries. For example, if you want to calculate the annual rainfall in the UK (just to find a good holiday place for yourself), the model will receive the daily rainfall for ten years, calculate the average value, and pass it to the view.

III. controller)

Simply put, the controller is the first part of the HTTP request to be called in a Web application. It checks received requests, such as GET variables, and makes appropriate feedback. Before writing your first controller, it is difficult for you to write 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. ?>

This code mix process-oriented and object-oriented code, but this is usually the best choice for small websites. The code above can be optimized. The controller is actually a control used to trigger the binding between the data of the model and the View elements.

Here is a simple example of using the MVC mode. First, we need a database category class, which is a common 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. ?>

Put the model on 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. ?>

Note: Between the model and the data pipeline class, the interaction between the model and the data pipeline class will never be more than one row-no multiple rows are transmitted, and the program will soon slow down. For classes in the usage mode, the same program only needs to keep one Row in the memory -- others are handed over to saved query resources -- in other words, we asked MYSQL to 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. ?>

Finally, the controller implements 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: 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. ?>

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 a way to demonstrate the mode. 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. ?>

There are some techniques for using controllers. you can do this in PHP: $ this-> {$ _ GET ['method']} ($ _ GET ['param']); we recommend that you define the namespace format (namespace) of the program URL so that it will be more standard, for example:

  1. "Index. php? Class = ProductView & method = productItem & id = 4"

The controller can be processed as follows:

  1. $ View = new $ _ GET ['class'];
  2. $ View-> {$ _ GET ['method'] ($ _ GET ['id']);

Sometimes it is not easy to establish a controller, for example, when the development speed and adaptability need to be weighed. A good place to be inspired is Apache group's Java Struts. its controller is completely defined by the XML document.

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.