MVC mode PHP implementation author Harry Fuecks Source http://www.phpe.net/ 2004-06-15
The MVC mode is very common in the website architecture. It allows us to build a three-story application, separating a useful layer from your code, helping designers and developers working together and improve our maintenance and expanding existing program.
view(
View
)
"View" mainly refers to our final result of the web browser - such as the HTML generated by our script. When it comes to the view, many people think of the template, but the correctness of the template scheme is worthy of being questionable. For view, the most important thing may be that it should be "self aware", and the view is rendered (render), the elements of the view can realize that they are in a larger framework. Take XML as an example, you can say that XML is in parsing, the DOM API has such a cognition - a node in a DOM tree know where it is and what it contains. (When the node in an XML document is parsed with SAX, it is only meaningful when resolving it to the node.) Most template schemes use simple procedure language and such template tags:
{some_text} p>
{some_more_text} p> They have no meaning in the document, and their representative is just that PHP will replace it with other things.
If you agree to this loose description of the view, you will agree to the vast majority of template schemes and there is no effective separation view and model. Template tags will be replaced in what stored in the model.
When you implement the view, ask yourself a few questions: "Is there a replacement of all views?" "How long does it take to implement a new view?" "Can I easily replace the description language of the view? (For example, use SOAP in the same view Document replacement HTML document) "
model(
MODEL
)
The model represents the program logic. (Business Layer) is often referred to in enterprise-class procedures
In general, the model's task is to convert the original data into data containing certain significance, which will be displayed by the view. Typically, the model will pick up the data query, which may be inquired by some abstract data classes (data access layers). For example, you want to calculate the British annual rainfall (just to find a better holiday), the model will receive a daily rainfall in ten years, calculate the average, and then pass to the view.
Controller (
Controller
)
A simple saying that the controller is part of the HTTP request that is entered in a web application. It checks the request received, such as some Get variables, making appropriate feedback. It is difficult to start writing other PHP code before writing your first controller. The most common usage is the structure of INDEX.PHP in 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 ();?> This code mixed the code-oriented process and object, but for a small site, this is usually the best choice. Although the code on the upper side can be optimized.
The controller is actually used to trigger the binding control between the data and view elements of the model. example
Here is a simple example of using the MVC mode. First we need a database access class, which is a normal 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;}}?> Play the model on it.
php / ** * fetches "Products" from the database * / class productmodel {/ ** * private * $ DAO an instance of the dataaccess class * / var $ dau; //! 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 PROMITS LIMIT". $ start. "," $ rows);} //! a manipulator / ** * tells the $ dboject to store query ask a resource * @Param $ ID A Primary Key for a Row * @Return Void * / Function ListProduct ($ THIS-> DAO-> FETCH ("Select * from products where produter. $ ID." '";} / /! A manipulato r / ** * 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 between the model and data access classes, their interactions will never be more than one line - no multi-line is transmitted, so it will slow down. The same program For the use of the mode, it only needs to keep a line (ROW) - other handed Query Resource - in other words, we let MySQL keep our results for us. Next is the view - I have dropped HTML to save space, you can view the full code of this article.
?
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 is just a method of demo mode. Our index.php files look like this:
$ this -> {$ _ get ['Method']} ($ _ get ['param']); a suggestion is that you better define the namespace form of the program URL, which will compare the specification such as:
"Index.php? Class = ProductView & Method = ProductITEM & ID = 4"
Through it we can handle our controller: $ view = new $ _GET ['Class']; $ View -> {$ _ get ['Method'] ($ _ get ['id']); sometimes, establish control The device is difficult, such as when you trade between the development speed and adaptability. A good place to get inspiration is apache group
Java Struts, its controller is completely defined by the XML document. @
Full program