search
HomeBackend DevelopmentPHP TutorialExample of php implementing mvc mode

  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. } p>
  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. ?>
  51. > ;
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. /**
  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
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment