The following small series will bring you a simple example code of phpMVC message book (mandatory ). I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the following small series to bring you a simple php MVC message book instance code (this article is required ). I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.
Abstract on the title, I call this message board the simplest. In fact, it should be called the simplest. because I focus all my attention on the design and implementation of the MVC mode, there is almost no modification to the UI.
This small program contains 6 files, in which index.php is the program access port; post.htm is the message form, and the Model, View, and Controller files in the lib folder implement MVC, respectively. DataAccess is a simple database access class. In fact, this program is written by a foreign user.
PHP code:
/*** A class used to access MySQL * only implements the basic functions required for demonstration, and there is no fault tolerance. * The code has not been modified. just translate the comments, added your own experience */class DataAccess {var $ db; // used to store the database connection var $ query; // used to store the query source //! Constructor. /*** create a new DataAccess object * @ param $ host database server name * @ param $ user database server username * @ param $ pass password * @ param $ db database name * /function _ construct ($ host, $ user, $ pass, $ db) {$ this-> db = mysql_pconnect ($ host, $ user, $ pass); // connect to the database server mysql_select_db ($ db, $ this-> db ); // select the required database // pay special attention to the difference between $ db and $ this-> db // The former is the constructor parameter // The latter is the data member of the class }//! Run the SQL statement/*** to execute the SQL statement, obtain a query source and store it in the data member $ query * @ param $ SQL statement string executed * @ return void */function fetch ($ SQL) {$ this-> query = mysql_unbuffered_query ($ SQL, $ this-> db); // Perform query here }//! Obtain a record/*** returns a record of the query result in an array. you can call this function cyclically to traverse all records * @ return mixed */function getRow () {if ($ row = mysql_fetch_array ($ this-> query, MYSQL_ASSOC) // The MYSQL_ASSOC parameter determines that the array key name uses the field name to indicate return $ row; elsereturn false;}?>
Next we will introduce the Model class.
This class is also very simple, and the functions in it can be seen at a glance, it is for a variety of data operations, it accesses the database through DataAccess.
PHP code:
//! Model class/*** the main part of the Model class is the function corresponding to various data operations in the message book * such as the display, insertion, and deletion of message data */class Model {var $ dao; // An instance (object) of the DataAccess class )//! Constructor/*** constructs a new Model object * @ param $ dao is a DataAccess object * this parameter is passed by address (& $ dao) in the form of $ this-> dao * Model, and saved in the Model's member variable $ this-> dao, the * Model calls $ this-> dao's fetch method to execute the required SQL statement */function __ construct (& $ dao) {$ this-> dao = $ dao;} function listNote () {// get all messages $ this-> dao-> fetch ("SELECT * FROM note ");} function postNote ($ name, $ content) {// INSERT a new message $ SQL = "INSERT INTO 'test '. 'note' ('id', 'name', 'content', 'ndate', 'ADD') VAL UES (NULL, '$ name',' $ content', NULL, NULL); "; // echo $ SQL; // for complex SQL statements, // use echo to output the output during debugging to see if it is correct. this is a common debugging technique. $ this-> dao-> fetch ($ SQL);} function deleteNote ($ id) {// DELETE a message. $ id is the id of the message. $ SQL = "DELETE FROM 'test '. 'note' WHERE 'id' = $ id; "; // echo $ SQL; $ this-> dao-> fetch ($ SQL);} function getNote () {// Obtain a message stored as an array // View reads data from the query result using this method and displays if ($ note = $ this-> dao-> getRow ()) return $ note; elsereturn fal Se ;}}?>
After reading these two classes, you may find that they are similar to the ones we used to write programs. But now, we still cannot hear about MVC. if you do not understand MVC, on the basis of these two classes, you can start to write your previous programs. For example, to display all messages, you only need to write the following code:
PHP code:
Require_once ('Lib/DataAccess. php '); require_once ('Lib/Model. php '); $ dao = & new DataAccess ('localhost', 'root', '', 'test'); $ model = & new Model ($ dao ); $ model-> listNote (); while ($ note = $ model-> getNote () {$ output. = "name: $ note [name] message: $ note [content]";} echo $ output;?>
Very kind, huh, huh.
With this "emotional foundation", you will not be afraid of MVC. next we will go to the main course today, that is, the "Controller" debut!
First, let's take a general look at the main structure. It includes a Controller class and three derived sub-classes (listController corresponds to the message display function, postController corresponds to the message posting function, and deleteController corresponds to the message deletion function ).
PHP code:
//! Controller/*** set different parameters (list, post, and delete) in $ _ GET ['action) * corresponding to the subclass that completes this function control */class Controller {var $ model; // Model object var $ view; // View object //! Constructor/*** constructs a Model object stored in the member variable $ this-> model; */function _ construct (& $ dao) {$ this-> model = & new Model ($ dao);} function getView () {// Obtain The View function // return the view object View // The Controller subclass corresponding to the specific function generates the corresponding View subclass object // return the result to the external caller through this function return $ this-> view ;}} // controls the class listController extends Controller that is used to display the message list {// extends indicates inheriting function _ construct (& $ dao) {parent ::__ construct ($ dao ); // inherit the constructor of the parent class // The meaning of this row can be simply understood as: // Construct the parent class Copy the function code $ this-> view = & new listView ($ this-> model ); // create an object of the corresponding View subclass to display the object // pass the model object to the View subclass for data retrieval} // controls the subclass class postController extends Controller {function _ construct (& $ dao, $ post) {parent ::__ construct ($ dao); $ this-> view = & new postView ($ this-> model, $ post ); // the real parameter of $ post is $ _ POST array // The Message items in the form are stored in this system array.} // class deleteController extends Controller {function _ _ construct (& $ da O, $ id) {parent ::__ construct ($ dao); $ this-> view = & new deleteView ($ this-> model, $ id) ;}}?>
After a general view, you must start to study it carefully. Don't worry. in order to be aware of it, let's first look at the macro perspective and see how index. php calls Controller at the entrance:
PHP code:
Php //! Index. php total entry/*** index. php call form: * show all messages: index. php? Action = list * add statement: index. php? Action = post * delete message: index. php? Action = delete & id = x */require_once ('Lib/DataAccess. php '); require_once ('Lib/Model. php '); require_once ('Lib/View. php '); require_once ('Lib/Controller. php '); // Create a DataAccess object (modify the parameter value as needed) $ dao = & new DataAccess ('localhost', 'root ','', 'test'); // call different controller subclasses based on the values of $ _ GET ["action"] $ action =$ _ GET ["action"]; switch ($ action) {case "post": $ controller = & new postController ($ dao, $ _ POST); break; case "list": $ Controller = & new listController ($ dao); break; case "delete": $ controller = & new deleteController ($ dao, $ _ GET ["id"]); break; default: $ controller = & new listController ($ dao); break; // The default value is show message} $ view = $ controller-> getView (); // Get The view object $ view-> display (); // output HTML?>
Index. php makes it clearer. the original function is specified through $ _ GET ["action"] and distributed by a switch structure. different functions correspond to different Controller subclasses. Now you can roll it up (the abbreviation of rolling the page up is not an unclean term ^_^) and take a closer look at this Controller code. The comments should be very detailed. if you do not understand them, let's look at the OOP syntax and concepts of PHP5. simply looking at these concepts, the better the hypnosis effect is, and now let's look at them with actual problems, it should be different. However, I suggest you work hard to lay the foundation of OOP after finishing the MVC Hello World and knowing what happened to MVC. after all, that is the root cause.
What's the matter? the Controller is really a guy who just doesn't know how to practice it. if you don't see three lines, it will lead you to the View. let's take a look at the View.
View has a subclass to Display corresponding functions. After understanding the Controller, the View code is not ugly. if it is ugly, it is also because of the combination of HTML. what it does is to obtain the required data from the Model and then plug it into the HTML.
PHP code:
//! View class/*** various View subclasses for various functions (list, post, and delete) are called by the Controller to display webpages with different functions */class View {var $ model; // Model object var $ output; // string used to save the output HTML code //! The Constructor/*** receives and stores the Model object in the parameter in the member variable $ this-> model * for the subclass to obtain data through the model object */function _ construct (& $ model) {$ this-> model = $ model;} function display () {// outputs the final formatted HTML data echo ($ this-> output );}} class listView extends View // subclass of displaying all messages {function _ construct (& $ model) {parent ::__ construct (& $ model ); // inherit the constructor of the parent class (see Controller for details) $ this-> model-> listNote (); while ($ note = $ this-> model-> getNote ()) // Obtain data row by row {$ this -> Output. = "name: $ note [name]: $ note [content] delete ";}}} class postView extends View // subclass of the comments {function _ construct (& $ model, $ post) {parent ::__ construct (& $ model ); $ this-> model-> postNote ($ post [name], $ post [content]); $ this-> output = "Note Post OK! View ";}} class deleteView extends View // delete the comments subclass {function _ construct (& $ model, $ id) {parent ::__ construct (& $ model ); $ this-> model-> deleteNote ($ id); $ this-> output = "Note Delete OK! View ";}}?>
The reason why the UI is so simple is that these jobs can be handed over to templates such as Smarty. here we are like focusing on MVC and don't want to drag Smarty in, so we can combine it. in the future, we can combine Smarty.
After reading this, I wonder if you have understood the concept and implementation of MVC.
I am also a beginner. this is a masterpiece based on Huludao. I want to know about MVC. if you are a master, I 'd like to hear from you, does such division and architecture conform to the MVC philosophy? What else should be improved?
Of course, we all know that there are a lot of arguments about MVC, which is normal. just like the arguments about development languages, there will never be any more, and academic arguments will help innovation. As we learn technology and use technology, we must study it in depth, master the basic usage, and then discuss it. this is the development of a higher level, it is only a waste of time to argue where you are confused.
The following describes the benefits of MVC that I have learned. it does bring convenience to the function expansion of the program. for example, we want to add a function to query messages by user name, you only need to add a query function to the Model (the usage of these functions is similar to the stored procedure), and add the corresponding subclass to the Controller and View, the advantage of this separation is that the functional modules of the program can be plug and play, and the logic of the entire program is very clear. I think this feature may be of great value for Web applications with frequent changes in requirements.
The above is all the content of a simple php MVC message Library example code (which must be read) provided by the editor. I hope it will help you and support me a lot ~