Home Backend Development PHP Tutorial Example of php implementing mvc mode

Example of php implementing mvc mode

Jul 25, 2016 am 09:05 AM

  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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles