The MVC pattern is very common in website architecture. It allows us to build a three-tier application, separating useful layers from the code, helping designers and developers work together and improving our ability to maintain and extend existing applications.
View
"View" mainly refers to the final result we send to the web browser - such as the HTML generated by our script. When talking about views, many people think of templates, but the correctness of calling template solutions views is questionable.
Probably the most important thing about a view is that it should be "self aware". When the view is rendered, its elements are aware of their role in the larger framework.
Taking XML as an example, it can be said that when XML is parsed, the DOM API has such knowledge that a node in the DOM tree knows where it is and what it contains. (When a node in an XML document is parsed with SAX it only makes sense when the node is parsed.)
Most template schemes use simple procedural languages and template tags like this:
<p>{some_text}</p >
<p>{some_more_text}</p>
They have no meaning in the document, all they mean is that PHP will replace it with something else.
If you agree with this loose description of views, you will also agree that most template solutions do not effectively separate views and models. The template tag will be replaced with whatever is stored in the model.
Ask yourself a few questions as you implement the view: "Is it easy to replace the entire view?" "How long does it take to implement a new view?" "Is it easy to replace the view's description language? (For example, using SOAP in the same view Document replaces HTML document)"
Model (Model)
The model represents the program logic. (Often called the business layer in enterprise-level programs)
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, the model will encapsulate data queries, perhaps through some abstract data class (data access layer) to implement the query. For example, if you wish to calculate the annual rainfall in the UK (just to find yourself a nice holiday spot), the model will receive the daily rainfall for ten years, calculate the average, and pass it to the view.
Controller (controller)
simply means that the controller is the first part of the incoming HTTP request in the web application. It checks the received request, such as some GET variables, and makes appropriate feedback. It's difficult to start writing other PHP code until you write your first controller. The most common usage is a structure like 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 mixes procedural and object-oriented code, but for small sites, this is usually the best choice. Although the above code can still be optimized.
Controllers are actually controls used to trigger bindings between the model's data and view elements.
Example
Here is a simple example using the MVC pattern.
First we need a database access class, which is an ordinary 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 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 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 the interaction between the model and the data access class is never more than one line - no multiple lines are sent, which will quickly slow down the program. The same program only needs to retain one row (Row) in memory for the class using the schema - the rest is given to the saved query resource (query resource) - in other words, we let MYSQL maintain the results for us.
Next up is the view - I removed the HTML to save space, you can check out the full code in this post.
<?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;
}
}
?>
Summary: The MVC pattern is very common in website architecture. It allows us to build a three-tier application, separating useful layers from the code, helping designers and developers work together and improving our ability to maintain and extend existing applications. This article will introduce you to the implementation of the MVC pattern in PHP.
Tags: PHP MVC MVC pattern PHP website
Oracle helps you gain accurate insight into each logistics link
Oracle helps you gain accurate insight into each logistics link. Finally, the controller, we will implement 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 controllers to implement models and integrate views at the same time. This is just one way to demonstrate the pattern.
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 tricks for using controllers, in PHP you can do this:
$this->{$_GET['method']}($_GET['param']);
One suggestion is that you better define the program URL Namespace form (namespace), then it will be more standardized, for example:
"index.php?class=ProductView&method=productItem&id=4"
Through it we can process our controller like this:
$view=new $_GET['class'];
$view->{$_GET['method']($_GET['id']);
Sometimes, building a controller is difficult, such as when you trade off development speed and adaptability. A good place to get inspiration is the Apache group's Java Struts, whose controllers are entirely defined by XML documents.