Implementation analysis of PHPMVC in website architecture _ PHP Tutorial

Source: Internet
Author: User
Implementation analysis of PHPMVC in website architecture. 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, 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 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 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.

<?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.
/**
* 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();
}
}
?>

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

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 isApacheGroupJavaStruts. its controller is completely defined by the XML document.

View refers to the final result that 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 model...

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.