The implementation analysis of PHP MVC pattern in Web site architecture _php Skills

Source: Internet
Author: User
Tags constructor html page http request mixed

Views (view)

"View" mainly refers to the end result we sent to the Web browser?? Like the HTMLthat our script generates. 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 about the view is that it should be "self aware", and when views are rendered (render), the elements of the view are aware of their role in the larger frame .

In the case of XML , it can be said that when XML is parsed, the DOM API has this knowledge?? A node in a DOM tree knows where it is and what it contains. (When a node in an XML document is parsed with sax, it makes sense only if it is resolved to that node.) )

The vast majority of template schemes use simple process languages and such template tags:


{Some_more_text}

They don't make sense in the document, they mean only that PHP will replace it with something else.

If you agree with this loosely described view, you will agree that most template schemes do not have a valid separation of views and models. The template label will be replaced with what is stored in the model.

Ask yourself a few questions when you implement the view: Is it easy to replace the whole view? "" How long does it take to implement a new view? Can you easily replace the description language of a view? (such as replacing an HTML document with a SOAP document in the same view) "

Models (model)

The model represents the program logic. (often referred to as the business layer (business layer) in an enterprise-level program)

In general, the task of the model is to convert the original data into data that contains some meaning, which will be displayed by the view. Typically, a model encapsulates a data query, possibly through some abstract data class (data access layer). For example, if you want to calculate the annual rainfall in the UK (just to find yourself a better place to go for a vacation), the model will receive the daily rainfall of the decade, calculate the average, and pass it on to the view.

Controller (Controller)

Simply put, the controller is part of the first invocation of the HTTP request entered in the Web application. It checks for incoming requests, such as some get variables, to make appropriate feedback. Before you write your first controller, it's hard to start writing other PHP code. The most common usage is the structure of a index.php like a switch statement:














? >

This code is mixed with procedures and object -oriented code, but for small sites, this is usually the best choice. Although the above code can also be optimized.

The controller is actually a control that triggers the binding between the data and view elements of the model.

Example

Here is a simple example of using the MVC pattern.

First we need a database access class, which is a generic class.

<?php
/**
* A Simple class for queryingMySQL
*/
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 and stores it in a
* @param $sql string The database query to run
* @return void
*/
function Fetch ($sql) {
$this->query=mysql_unbuffered_query ($sql, $this->db)















? >

Put the model on top of 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
* @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 the products WHERE productid= '". $id. "");
}

//! A Manipulator
/**
* Fetches a product as a 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 between model and data access classes, they don't interact more than one row.? No more lines are transmitted, which slows down the program quickly. The same program for classes that use patterns, it only needs to keep one row in memory (row)?? Others to the saved query resource (query resource)?? In other words, we let MySQL keep the results for us.

Next is the view?? I removed the HTML to save space and you can view the full code for 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 this 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 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, we will implement the view as a subclass.































? >

498) this.style.width=498; "Border=0>

Note that this is not the only way to implement MVC?? For example, you can use the controller implementation model to integrate the view at the same time. This is just one way of demonstrating patterns .

Our index.php file looks like this:











? >

Beautiful and simple.

We have some tips for using controllers that you can do in PHP:

$this->{$_get[' method ']} ($_get[' param '));

One suggestion is that you'd better define the name space form (namespace) of the program URL, so that it will compare specifications such as:

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

Through it we can handle our controllers like this:


$view->{$_get[' method '] ($_get[' id '));

Sometimes it's hard to build a controller, such as when you're balancing development speed and adaptability. A good place to get inspired is the apache Group The Java Struts, whose controller is entirely defined by an 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.