A simple PHP MVC message This instance code (must see article) _php instance

Source: Internet
Author: User
Tags mixed

Summary Title I put this message board is the simplest, in fact, should be called the most humble, because the whole focus on the MVC pattern design and implementation, so the UI aspect is almost no modification.

This small program contains 6 files, where index.php is the program entrance, post.htm is the message form, in the Lib folder model, View, controller three files to achieve mvc,dataaccess is a simple database access class. In fact, this program is written by a person from abroad.

PHP Code:

/** * A class to access MySQL * only to implement the basic functions required for demo, no fault tolerance, etc. * code is not modified, just translate the annotation, add a point of their own experience * * Class DATAAC 
Cess {var $db;//used to store the database connection var $query;//To store the query source//! constructor. /** * Create a new DataAccess object * @param $host database server name * @param $user Database Server user name * @param $pass password * @param $db database name * * Nction __construct ($host, $user, $pass, $db) {$this->db=mysql_pconnect ($host, $user, $pass);//Connect database server Mysql_select _db ($db, $this->db); Select the desired 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}//! Execute SQL statement/** * Execute SQL statement, get a query source and store in data member $query * @param $sql executed SQL statement String * @return void/function Fetch ($sql) {$th Is->query=mysql_unbuffered_query ($sql, $this->db); Perform query here}//! Get a record/** * Returns a row of the query results in an array that iterates through the entire record * @return Mixed/function GetRow () {if ($row =mysql_fetch_array ($t 
HIS->QUERY,MYSQL_ASSOC)//mysql_assoc parameter determines that the array key name represents the return $row with the field name; 
else return false; } 

Next to introduce the model class.

This class is also very simple, the inside of the function is known, is for a variety of data operations, it through the DataAccess access to the database.

PHP Code:

//! Model Class/** * Its main part is corresponding to the message of the various data manipulation functions * such as: message data display, insert, delete and so on * * Class Model {var $dao;//dataaccess (object)//! constructor/ * * Construct a new Model object * @param $dao is a DataAccess object * This parameter is passed to model * in the form of address delivery (& $dao) and saved in the member variable $this->dao of model * Mode 
L EXECUTE the required SQL statement by calling the $this->dao fetch method */function __construct (& $dao) {$this->dao= $dao; 
function Listnote () {//Get all message $this->dao->fetch ("select * from"); function Postnote ($name, $content) {//Insert a new message $sql = "INSERT INTO ' test '. ' Note ' (' id ', ' name ', ' content ', ' ndate ', ') ' 
DD ') VALUES (null, ' $name ', ' $content ', null, NULL); "; Echo $sql; 
For more complex synthesis of SQL statements,//When debugging with echo output to see if the correct is a common debugging skills $this->dao->fetch ($sql); 
function Deletenote ($id) {//delete a message, $id is the ID of the message $sql = "Delete from ' Test '. ' WHERE ' id ' = $id;"; 
Echo $sql; 
$this->dao->fetch ($sql);  
function Getnote () {//Get a message stored as an array//view use this method to read the data from the query results and display if ($note = $this->dao->getrow ()) return $note; 
else return false; } 
}?> 

After reading these two classes you may find that this is similar to the previous program we wrote, and it does not yet smell MVC, and if you don't understand MVC, you can start writing your previous program on the basis of these two classes. For example, to display all the comments, just write down the 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 bar, hehe.

With this "emotional basis" you will not be intimidated by MVC, the following we will be on the main course today, that is "Controller" shiny debut!

Look at the main structure first, which includes a controller class and three subclasses (Listcontroller corresponds to the display message function, Postcontroller corresponding to the release of the message function and Deletecontroller corresponding delete message function).

PHP Code:

//! Controller/** * Controller will $_get[the different parameters in ' action ' (list, post, delete) * corresponds to the corresponding subclass that completes the function control/class Controller {var $model;//M Odel object var $view; View Object//! 
Constructor/** * Constructs a model object that is stored in a member variable $this->model; 
* * Function __construct (& $dao) {$this->model=& New model ($DAO); function GetView () {//Get View function//return views///function controller subclass to generate the corresponding view subclass object//returns to the external caller return $this->v 
Iew; The subclass class Listcontroller extends controller{//extends that controls the display of the message list represents the Inheritance function __construct (& $dao) {Parent :: __construct ($dao); 
The constructor that inherits its parent class//The meaning of the line can be easily understood as://copying the constructor code of its parent class $this->view=& new ListView ($this->model); Create an object of the corresponding view subclass to complete the display///Pass the Model object to the view subclass for data}////To control the subclass class Postcontroller extends controller{function _ 
_construct (& $dao, $post) {parent::__construct ($dao); 
$this->view=& New Postview ($this->model, $post); The $post arguments are stored in the system array in the $_post array//form for the message item}///To control the subclass class Deletecontroller of the delete message ExteNDS controller{function __construct (& $dao, $id) {parent::__construct ($dao); 
$this->view=& New Deleteview ($this->model, $id); }}?>

After general browsing, you must begin to study it carefully, do not worry, in order to know, we first look at the macro, first see how the total entrance index.php is called Controller:

PHP Code:

 PHP//!index.php General Entry/** * index.php call form: * Show all messages: Index.php?action=list * Add message 
: 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 DataAccess objects (please modify the parameter values according to your needs) $dao =& new DataAccess (' localhost ', ' root ', ' ', ' test '); 
  
  
Different controller subclasses are called according to the $_get["action" values $action =$_get["action"]; 
Switch ($action) {case "POST": $controller =& New Postcontroller ($dao, $_post); Case "List": $controller =& new Listcontroller ($dao); 
Break Case "Delete": $controller =& New Deletecontroller ($dao, $_get["id")); 
Break Default: $controller =& new Listcontroller ($dao); Break Default to display message} $view = $controller->getview (); Gets the View object $view->display (); Output HTML?> 

After seeing the index.php, you know better, the original function is specified by $_get["action", distributed by a switch structure, different functions correspond to different controller subclasses. Now you can roll up (the short name of the scrolling page, not the unclean language ^_^) take a closer look at this controller code. Note should be very thin, do not understand the place to see PHP5 oop grammar and concept bar, pure look at these concepts are always the more hypnotic effect of the better, now with practical problems to see, should be different. But I would suggest that you do the basics of OOP after you've finished this MVC Hello World and you know how MVC is going to work.

How, controller is really a light talk not practice of the guy, see less than three lines it will lead you to view, then look at the view bar.

View has a corresponding subclass, responsible for the display of the corresponding functions. Understand the Controller,view code is not ugly, ugly is also because of the mixed HTML reason, it is done is to get the required data from model, and then into the HTML.

PHP Code:

//! View Class/** * The various view subclasses for each function (list, post, delete) are controller called to complete different functions of the Web page display/class View {var $model;//model Object Var $output; String//! to save the output HTML code Constructor/** * takes the model object in the parameter and stores it in the member variable $this->model * for subclasses to get data via model Object * * Function __construct (& $model) {$thi 
S->model= $model; 
function display () {//Output the final formatted HTML data echo ($this->output); Class ListView extends View//show subclasses of all messages {function __construct (& $model) {parent::__construct (&am p; $model); 
Inherits the constructor of the parent class (see Controller) $this->model->listnote (); 
while ($note = $this->model->getnote ())//line by row get data {$this->output.= "name: $note [name] message: $note [content] Delete"; }} class Postview extends View//Post message Subclass {function __construct (& $model, $post) {Parent::__const 
Ruct (& $model); 
$this->model->postnote ($post [name], $post [content]);
$this->output= "Note Post ok! 
View "; } class Deleteview extends View//delete messageSubclass {function __construct (& $model, $id) {parent::__construct (& $model); 
$this->model->deletenote ($id);
$this->output= "Note Delete ok! 
View ";
  }}?>

The reason why the UI is so shabby is because these jobs can be given to templates like Smarty, and we're here to focus on MVC, don't want to pull smarty in, so it's okay, so we can combine smarty in the future.

After looking at this thing, I wonder if you understand more about the concept and implementation of MVC.

I am also a beginner, this is a gourd painting gourd, the purpose is to understand MVC, if you are a master, I would like to get your comments, such a division and the structure is consistent with the concept of MVC? What else should be improved?

Of course, we all know that there's a lot of debate about MVC right now, and it's normal, like the debate about developing languages, endlessly, and that academic debate can help innovation. As we learn technology, using technology, we must be steadfast in-depth study, master the basic usage and then to discuss, that is a higher level of development, in their own are not clear where the argument can only be a waste of time.

Here's what I've learned about the benefits of MVC, and it does make it easier to extend the functionality of the program, such as the example we want to add a query based on the user name, just add a query function in the model (suddenly found that the use of these functions is very much like stored procedures), Controller and view add the corresponding subclass, the advantage of this separation is that the program function module can plug and Play, and the whole program logic is very clear. I think this feature may be valuable for Web applications that have frequent changes in demand.

The above is a small series for everyone to bring a simple PHP MVC message This example code (must read) all the content, I hope to help you, a lot of support cloud Habitat Community ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.