Implementation and Analysis of php mvc pattern in website architecture

Source: Internet
Author: User

View)

"View" mainly refers to the final result we send to the Web browser ?? For example,Html. When it comes to views, many people think of templates,TemplateThe correctness of the scheme called view is questionable.

The most important thing for a view is probably that it should be self aware. When a view is rendered, the view elements can realize that they are larger.Framework.

ToXMLFor example, when XML is parsed, does dom api have 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 are meaningless in the document, and they represent onlyPHPIt will be replaced 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 representsProgramLogic. (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 PHPCode. 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 uses both process-oriented andObjectBut for small sites, this is usually the best choice. 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 needDatabaseCATEGORY class, which is a common class.

 
      /** 
* 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);
}< br>
//! 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 this article.ArticleComplete code.

<? 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.
/**
* Constucts a new productview object
* @ Param $ model an instance of the productmodel class
*/
Function productview (& $ model ){
$ This-> model = & $ model;
}

//! A Manipulator
/**
* Builds the top of an HTML page
* @ Return void
*/
Function header (){

}

//! A Manipulator
/**
* Builds the bottom of an HTML page
* @ Return void
*/
Function footer (){

}

//! A Manipulator
/**
* Displays a single product
* @ Return void
*/
Function productitem ($ id = 1 ){
$ This-> model-> listproduct ($ id );
While ($ Product = $ this-> model-> getproduct ()){
// Bind data to HTML
}
}

//! A Manipulator
/**
* Builds a product table
* @ Return void
*/
Function producttable ($ rownum = 1 ){
$ Rowsperpage = '20 ';
$ This-> model-> listproducts ($ rownum, $ rowsperpage );
While ($ Product = $ this-> model-> getproduct ()){
// Bind data to HTML
}
}

//! An accessor
/**
* Returns the rendered html
* @ Return string
*/
Function display (){
Return $ this-> output;
}
}
?>

Finally, the Controller implements the view as a subclass.

<? PHP
/**
* Controls the application
*/
Class productcontroller extends productview {

//! A constructor.
/**
* Constucts a new productcontroller object
* @ Param $ model an instance of the productmodel class
* @ Param $ getvars the incoming http get method Variables
*/
Function productcontroller (& $ model, $ getvars = NULL ){
Productview: productview ($ model );
$ This-> header ();
Switch ($ getvars ['view']) {
Case "product ":
$ This-> productitem ($ getvars ['id']);
Break;
Default:
If (empty ($ getvars ['rownum']) {
$ This-> producttable ();
} Else {
$ This-> producttable ($ getvars ['rownum']);
}
Break;
}
$ This-> footer ();
}
}
?>

Note that this is not the only way to implement MVC ?? For example, you can use a controller to integrate the model with the view. This is only a demonstration mode.Method.

Our index. php file looks like this:

<? PHP
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 ();
?>

Beautiful and simple.

We have some techniques for using controllers. You can do this in PHP:

$ This-> {$ _ Get ['method']} ($ _ Get ['param']);

One suggestion is that you 'd better define the namespace format (namespace) of the program URL, so that it will be more standard:

"Index. php? Class = productview & method = productitem & id = 4"

With this, we can process our controller as follows:

$ View = new $ _ Get ['class'];
$ View-> {$ _ Get ['method'] ($ _ Get ['id']);

sometimes it is very difficult to establish a controller, for example, when you weigh between development speed and adaptability. 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.