"Original translation" recognizes MVC design Patterns: The foundation of Web application openness (actual coding)

Source: Internet
Author: User
Tags php foreach yii

Translation: SHADOWMYDX reprint Please specify

In the first part of this series, I discussed the various parts of the MVC design pattern and their specific performance. In the second part, I talked about some common conventions for web development frameworks. The two parts of the article are the basis of this article, it is time to tell the real code. Personally, it is not difficult to understand the meaning of MVC, to theoretically understand the approximate process of MVC design patterns, and to follow the naming conventions of the framework, but if you start developing a project like this, you will quickly lose your way in the actual coding and eventually become a mess.

The problem is that the way MVC works is basically the opposite of what you've done so far. If you're a PHP programmer and you're developing a page that lists all departments (or the employee-department app), you're likely to write this PHP program:

    1. Create a new HTML page to include the header file in
    2. Connect to Database
    3. Querying the database
    4. Confirm Receipt of Query results
    5. Retrieving the returned query results through a loop
    6. Print the results of a query in some form of HTML, such as a table or list
    7. Close the database connection (or it may not be off)
    8. Complete the entire HTML page

This is what we need to do on even such a simple page. Even if you use the include file to process the database connection and introduce the template file to lay out the HTML, we still need to deal with a lot of logic. If you do the ability to show department details to another page by passing the Department ID in the URL, the page may also need to add some data validation steps. If you have a page that displays and processes a form at the same time, such as adding an employee, you need to add very, very much logic. This is not to say that there is something wrong with this development approach, but this approach is completely on the opposite side of the MVC design paradigm. You can imagine that MVC-style development is a pyramid, the model at the bottom, then to the controller, and finally a very small portion of the view.


As a principle of programming, the view requires only a little bit of work to do, and in most cases prints the value of the print variable. The most complex part of the view is best done by a conditional judgment statement to verify that a variable's value exists and prints, or to use a loop to print all the elements in the array. The view only produces what the user can see, so much more, nothing else. There is more logic in the controller, such as answering the user's actions, and playing an interface role between the model and the view. But there are some common mistakes, which is to put the code that should be in the model in the controller. The principle of an MVC design pattern is the "fat model, Thin Thin Controller" (SHADOWMYDX: The original is the Fat Model,thin controller, we take that meaning). This means that you should overwhelm the applied Foundation with more code (that is, the base of the pyramid-the model). I have read an article about MVC, which the author argues is that the function of the model is to maintain the state of the HTTP request. I think that's a great description, because maintaining the HTTP request state includes storing the data and processing the data. Storing data is like adding, modifying, and retrieving data through different requests in a departmental model, and processing data is like getting user-supplied data in a contact model, confirming that an email is sent. (shadowmydx: Stored data is stored in the original text, processing data as processed. doesn ' t necessarily get stored)

So what does this mean in real-world code? The first thing to be clear is that if your view file contains statements that are more than echo/print and have a little control structure, you may already be making a mistake. If you create a new variable in the view, it also means that you may have made a mistake. In fact, there should be very few PHP code running in the view, even if you use the Loop Print group should also choose the following form, focus on the HTML above.

<?php foreach ($departments as $n = $dept): ><li><?php echo $dept->something;?></li> <?php Endforeach;?>

The opposite is the way we use the usual PHP programs, with the emphasis on PHP code:

<?phpforeach ($departments as $n = $dept) {    echo ' <li> '. $dept->something. ' </li> ';}? >

Now it's time to talk about the code in the controller. The main task of the code in the controller is to control behavior, such as assigning functions and reacting to user input. The controller is a class that has some methods to do the actual work. These efforts include retrieving a specific model (for example, fetching a record from a table), invoking a model to complete the task of inserting, modifying, or deleting, and then invoking a view to present the results. The task of the model is the whole remaining part, such as executing a query statement, validating the data, and so forth. However, in the framework, most of the code for the model is already built-in, so you can invoke methods that are not defined by the model itself, such as Save or delete (these methods are inherited from the framework's model class).


Let's go back to the employee-sector example. Suppose now that you want to have a page that shows the names of all departments and department leaders. In the departmental model, where the department-led employee ID is stored, the controller can retrieve the entire department by invoking the model (the following is the syntax of the YII framework):

$dept = Departments::model ()->findall ();


$depts variables are passed to the corresponding view to print to the user. This is the basic way for Yii to use MVC, and of course, the departmental model does not actually define a findall () method, which is inherited.

Now you need to find the name of each department to make the view appear. In order to find that person's name, you need to get an employee model that is consistent with the storage ID in the departmental model. With Yii, the code is:

$emp = Employees::model ()->findbypk ($dept->departmentheadid);

This code means that you want a primary key value consistent with the current departmental model Departmentheadid values for the employee model. (in SHADOWMYDX:FINDBYPK, PK means primary key, which is the primary key)

One thing you absolutely can't do is to write similar query statements in the view, which is a disaster. Perhaps now you are more inclined to put the code into the controller, in order to achieve this, you need a loop to retrieve the departmental model, get Deparmentheadid, and then query the primary key with the employee model, and finally associate it with the corresponding department.

It should be clear that yii and most other frameworks support the connection of different models. In Yii, you can do this (of course you need to figure out the relationship between the models first):

$departments = Departments::model ()->with (' Employees ')->findall ();

However, if your framework does not have this functionality, or if there are no links between the two models, you can add the following method to the departmental model:

function Getdepartmenthead () {    $emp = Employees::model ()->findbypk ($this->departmentheadid);    if ($emp) {        return "$emp->lastname, $emp->firstname";    } else {        return ' unknown ';}    }

After defining this method, you don't need to add code to the controller. You can do this with a foreach loop in the view:

Echo $dept->getdepartmenthead;

 

Another important example is if you want to print the employee's name in the format lastname,firstname, or if you have a more complex output format, the method you write should be defined in the employee model, and then you can call this method anywhere you need to use the model. For example, what shows all employees, shows specific information about an employee, and shows department leaders and so on. Everything is for the reusability of the code.

Well, it's finally over. Have a question can go to the original author's page message

"Original translation" recognizes MVC design Patterns: The foundation of Web application openness (actual coding)

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.