Tutorials to .com

Tutorials to .com » Php » Others » MVC model to achieve the PHP

MVC model to achieve the PHP

Print View , by: iSee ,Total views: 4 ,Word Count: 2070 ,Date: Sun, 19 Apr 2009 Time: 9:05 PM

MVC model structure on the site are common. It allows us to build a three-tier application structure, separated from the code layer useful to help designers and developers work together, as well as to maintain and enhance our ability to expand existing programs.

View (View)

"View" mainly refers to the Web browser we have the final results - for example, our script-generated HTML. When it comes to view, many people thought that the template, but the view template is called the correctness of the program is questionable.

Of view, the most important thing is that it probably should be "self-consciousness (self aware)", the view was rendering (render), the view can be aware of the elements in a larger framework of their own role.

To xml for example, xml can be said to be resolved in, DOM API with this knowledge - a DOM tree node to know where it is and what it contains. (When a node in the xml document using SAX parsing only when the resolution to the node when it is to have any meaning.)

The vast majority of programs using a simple template language and so the process of template tags:

<p> (some_text) </ p>
<p> (some_more_text) </ p>


They are meaningless in the document, meaning they represent only php will use other things to replace it.

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

When you view the achievement of several questions to ask ourselves: "easy to replace the whole view of it?" "To achieve a new view of how long?" "Can easily view the description of the replacement language? (For example, in the same view with SOAP HTML document to replace the document) "


Model (Model)

Represents the logic model. (In the enterprise-level procedures are often referred to as the business layer (business layer))

Overall, the model's mission is to convert the original data contains some meaningful data will be shown in view. Typically, the model of the package of data information, may be through a number of abstract data type (data access layer) to achieve the query. For example, you want to calculate the annual rainfall in the UK (just to give you their holiday to find a better way), the model will receive a decade of daily rainfall, calculated average, send it to the view.


Controller (controller)

That the controller is a simple Web applications to access HTTP request as part of the first call. Inspection requests received by it, such as the number of GET variables, to make the appropriate feedback. You in writing before the first controller, is very difficult for you to start the preparation of other PHP code. The most common usage is like a switch statement in index.php of the structure:

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


Mix the code process and object-oriented code, but for small sites, it is usually the best option. Although the above code can also be optimized.

Controller model is used to trigger data and view elements of the binding between the controls.


Examples

Use here is a simple example of the MVC pattern.
First of all, we need a database access class, 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
* @ 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;
)
)
?>


Above model in its place.

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


It should be noted that, in the model and data access between the categories, and their interaction is not more than from his party - not to be multi-line transmission, as will soon make the program slow down. Program for the use of the same type of model, it needs to retain in his memory (Row) - to other resources saved query (query resource) - In other words, we allow for us to maintain the results of MYSQL.

Next is the view - I removed the 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, we will view the achievement of a sub-class.

<? 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 this is not the only way to achieve MVC - For example, you can use the controller to achieve integration at the same time view model. This is just a way to demo mode.

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 skills in the use of the controller, in PHP you can do:

$ this-> ($ _GET [ 'method']}($_ GET [' param ']);


One suggestion was that the definition of the procedure you had better Namespace URL of the form (namespace), as it would be more normative for example:

"index.php? class = ProductView & method = productItem & id = 4"


Through which we can deal with our controller:

$ view = new $ _GET [ 'class'];
$ view-> ($ _GET [ 'method']($_ GET [' id ']);


Sometimes, the establishment of the controller is a difficult task, for example, when you in the development of trade-off between speed and adaptability when. A good place for inspiration is the Apache group's java Struts, its controller is defined by the XML document.


php other Articles


Can't Find What You're Looking For?


Rating: Not yet rated

Comments

No comments posted.