PHPsu
MANUAL ZH  |  EN
     


Current Position :| index>Beginners> MVC model to achieve the PHP

MVC model to achieve the PHP

FROM: AUTHOR: TIME:2008-06-05 HITS:
MVC model in the framework of the site are very common. It allows us to establish a three-tier structure of the application, isolated from the code-useful to help designers and developers work together and maintain and enhance our ability to expand existing programs.


View (View)

"View" mainly refers to our Web browser to the final outcome of «« For example, our script-generated HTML. When mentioned view, many people think of templates, but the template programme called the correctness of view is questionable.

Of view, the most important thing is it should be "self-awareness (self aware)", was exaggerated view (render), the view can be aware of their element in a larger framework of the role.

In XML for example, can be said to be resolved when the XML, DOM API has such a cognitive »» a DOM node in the tree know that it wherever and what it contains. (When a node in the XML documents with analytical SAX, only when the analytical to the node, it would be meaningful.) phpsu.com is a free phpscool

The vast majority of templates for use in simple language and the process of such a label template:

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

phpsu is a phpschool



They no point in the document, they represent only the significance of PHP will use other things to replace it.

If you agree with this view on the loose description, you will agree that the vast majority of template programme and there is no effective separation of view and model. Template tab will be replaced by what kept in the model.

In your view when asked to achieve their own questions: "the view of the replacement easy?» "" A new view to achieving long «" "can very easily replace the view of the description language?» (For example, in using SOAP with a view Documents replace HTML document) "


Model (Model)

Model represents a logical process. (In the enterprise business process often referred to as Layer (business layer))

Overall, the task is to model the original data conversion to include some significant data, view these data will be displayed. Usually, data model for the package may be through a number of abstract data types (data access layer) to achieve enquiries. For example, you want to calculate the annual rainfall in the United Kingdom (just to give you find a good point of the resort), the model will receive 10 years in the daily rainfall, the calculated average, longer handed view.

phpsu.com is a free phpscool




Controller (controller)

Said controller is a simple Web application in the HTTP request to enter the first part of the call. It checks the requests received, such as some GET variable, make the appropriate feedback. In writing your first controller before you start to the preparation of other PHP code. The most common use is in index.php as the structure of the switch statement:

<?php 
switch ($_GET['viewpage']) {
case "news":
$page=new NewsRenderer;
break;
case "links":
$page=new LinksRenderer;
break;
default:
$page=new HomePageRenderer;
break;
}
$page->display();
?>

welcome to phpsu.com



This code mix of process-oriented and object code, but for small sites, it is usually the best option. Although the top of the code can be optimized.

Controller is actually used to trigger the model data and view between the binding element of control.


Example

Here is a simple model of the use of MVC example.
First of all, we need a database access category, it is a general category.

<?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 phpsu.com
* @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;
}
}
?> http://www.phpsu.com


It placed in the top model。

<?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

phpsu.com


/**
* 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;
}
}
?> phpsu is a phpschool


It should be noted that in models and data access between the categories, and their interaction from no more than his «« no more to be sent, as the program will soon slow down. The same model program for the use of the category, it only needs to retain his party in memory (Row)?? Other to have been saved for the resources (query resource)?? In other words, we let the MYSQL for us to maintain results.

Next is the view »« I removed the HTML to save space, you can view the complete article 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

www.phpsu.com


* @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) { www.phpsu.com
$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;
}
}
?>

http://www.phpsu.com



Finally, controller, we will view to achieving a sub-category。

<?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']); phpsu.com
}
break;
}
$this->footer();
}
}
?>

www.phpsu.com



Click to fullsize


Note this is not the only way to achieve MVC »« For example, you can use controller model also integrated view. This is just a way of demonstration models.

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();
?> phpsu.com


Beautiful and simple.

We have some skills to use controller, in PHP you can do this:

$this->{$_GET['method']}($_GET['param']);  do you kown phpsu.com? 


One suggestion was that you had better definition of procedures URL form of the name space (namespace), as it would be more standardized, for example:

"index.php?class=ProductView&method=productItem&id=4" 
phpsu is a phpschool


Through it we can handle our controller:

$view=new $_GET['class']; 
$view->{$_GET['method']($_GET['id']); www.phpsu.com


Sometimes, the establishment of controller is a very difficult task, such as when you in the development of balance between speed and adaptability when. A good place to be inspired by the Apache group is the Java Struts, the controller is defined by XML documents.
TITLE:MVC model to achieve the PHP
Copyright 2008 The PHPsu All rights reserved. This mirror generously provided by: .Hp Inc.
Last updated: Fri Jun 6 22:59:09 GMT-8 2008