Implementation of php mvc mode in website architecture

Source: Internet
Author: User

The MVC mode is very common in website architecture. It allows us to build a three-tier application that separates useful layers from code, helping designers and developers work together and improve our ability to maintain and expand existing programs.

View)

"View" mainly refers to the final result we send to the Web browser ?? For example, the HTML generated by our script. When it comes to views, many people think of templates, but the correctness of the template scheme called views is questionable.

The most important thing for a view is that it should be self-aware. When a view is rendered, view elements can be aware of their roles in a larger framework.

Taking XML as an example, we can say that when XML is parsed, the dom api has such cognition ?? A node in a DOM tree knows where it is and what it contains. (When a node in an XML document is parsed using SAX, it makes sense only when it is parsed to this node .)

Most template schemes use simple process languages and such template labels:

<P> {some_text} </p>
<P> {some_more_text} </p>

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 )"

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.

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:

<? Php
Switch ($ _ GET [viewpage]) {
Case "news ":
$ Page = new NewsRenderer;
Break;
Case "links ":
$ Page = new LinksRenderer;
Break;
Default:
$ Page = new HomePageRenderer;
Break;
}
$ Page-> display ();
?>

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.

Example

Here is a simple example of using the MVC mode.

First, we need a database category class, which is a common class.

<? Php
/**
* A simple class for querying MySQL
*/
Class DataAccess {
/**
* Private
* $ Db stores a database resource
*/
Var $ db;
/**
* Private
* $ Query stores a query resource
*/
Var $ query; // Query resource

//! A constructor.
/**
* Constucts a new DataAccess object
* @ Param $ host string hostname for dbserver
* @ Param $ user string dbserver user
* @ Param $ pass string dbserver user password
* @ Param $ db string database name
*/
Function DataAccess ($ host, $ user, $ pass, $ db ){
$ This-> db = mysql_pconnect ($ host, $ user, $ pass );
Mysql_select_db ($ db, $ this-> db );
}

//! An accessor
/**
* Fetches a query resources and stores it in a local member
* @ Param $ SQL string the database query to run
* @ Return void
*/
Function fetch ($ SQL ){
$ This-> query = mysql_unbuffered_query ($ SQL, $ this-> db); // Perform query here
}

//! An accessor
/**
* Returns an associative array of a query row
* @ Return mixed
*/
Function getRow (){
If ($ row = mysql_fetch_array ($ this-> query, MYSQL_ASSOC ))
Return $ row;
Else
Return false;
}
}
?>

Put the model above it.

<? Php
/**
* Fetches "products" from the database
*/
Class ProductModel {
/**
* Private
* $ Dao an instance of the DataAccess class
*/
Var $ dao;

//! A constructor.
/**
* Constucts a new ProductModel object
* @ Param $ dbobject an instance of the DataAccess class
*/
Function ProductModel (& $ dao ){
$ This-> dao = & $ dao;
}

//! A manipulator
/**
* Tells the $ dboject to store this query as a resource
* @ Param $ start the row to start from
* @ Param $ rows the number of rows to fetch
* @ Return void
*/
Function listProducts ($ start = 1, $ rows = 50 ){
$ This-> dao-> fetch ("SELECT * FROM products LIMIT". $ start. ",". $ rows );
}

//! A manipulator
/**
* Tells the $ dboject to store this query as a resource
* @ Param $ id a primary key for a row
* @ Return void
*/
Function listProduct ($ id ){
$ This-> dao-> fetch ("SELECT * FROM products where productid =". $ id ."");
}

//! A manipulator
/**
* Fetches a product as an associative array from the $ dbobject
* @ Return mixed
*/
Function getProduct (){
If ($ product = $ this-> dao-> getRow ())
Return $ product;
Else
Return false;
}
}
?>

One thing to note is that there will never be more interactions than one row between the model and the Data Pipeline class ?? If no multiple lines are transmitted, the program will soon slow down. For classes in the usage mode, the same program only needs to keep a Row in the memory )?? Other query resources are handed over to the saved query resource )?? In other words, let MYSQL keep the results for us.

Next is the view ?? I removed HTML to save space. You can view the complete code of this article.

<? Php
/**
* Binds product data to HTML rendering
*/
Class ProductView {
/**
* Private
* $ Model an instance of the ProductModel class
*/
Var $ model;

/**
* Private
* $ Output rendered HTML is stored here for display
*/
Var $ output;

//! A constructor.
& N

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.