A beginner's Guide to MVC

Source: Internet
Author: User
Tags php foreach ruby on rails

A beginner's Guide to MVC

2010-04-06 09:54:23 18839 times read 0 Reviews This article is grateful for something to offer Model-View-Controller (MVC)May be one of the most frequently mentioned patterns in network programming circles in recent years. People who are currently connected to the development of Web applications are not sure to hear and see this acronym for hundreds of times. Today, we will explain in detail The meaning of MVC, and why it has become so popular. The ancient History ...
MVC is not a design pattern, it is a Schema Mode(architectural pattern), which describes the structure of the application and the responsibilities and interactions of the parts of the structure.
It was first proposed in 1979, but the environment was somewhat different at the time, and the concept of network application did not exist at the moment. Tim Bernas Lee planted the seeds of the World Wide Web (WWW) in the early 90, and changed it forever. The model we are currently using in web development is actually an adapted version of the original model.
The crazy prevalence of this architectural pattern is due to the inclusion of this model in two extremely popular development frameworks, which are: Struts And Ruby on Rails。 These two development frameworks have a deep imprint on the hundreds of framework that was later born. the MVC pattern in Network application
The idea behind the model-view-Controller architecture pattern is simple: our application must differentiate between the following responsibilities: The application is divided into three main parts, each of which is responsible for different tasks. Let's take a look at a detailed explanation and an example.
Controller
The controller is in charge of the user's request (the controller receives an HTTP GET or POST request when the user clicks on an element on the graphical user interface (GUI) to perform the operation). Its primary function is to invoke and coordinate the required resources/objects to execute user requests. Typically the controller invokes the appropriate model for the task and selects the appropriate view. Model
A model is a data rule and data content that is shipped on top of the data, which generally corresponds to the object that the application is managing. In a software system, everything can be abstracted into a data model that can be processed in some way. What are the users, information, and books in the application? They are just a bunch of data that must be processed according to the corresponding rules (the date cannot be a future date, the e-Mail has a specific format, the length of the name cannot exceed the number of characters, and so on) the model gives the controller a data representation (such as information, books, albums) corresponding to the user's request content. No matter how we show the user, the data model will not change. This is why we are free to choose which view to use to present the data.
The model contains the most important components of our application logic, which are used in the process of the problem we are dealing with. The controller is more of an internal organizational logic that contains the application itself (more like a housekeeper).
View
Views provide different ways to present model data. It may be a template for data fills. The view can have more than one, and the controller determines which view to use. A network application is usually made up of many controllers, models, and views. A controller can be thought of as a host controller to receive all requests from a user, and then to invoke a specific controller to handle a different situation.
let's look at an example
Now, let's say we're developing an online bookstore. Users can do the following: View books. Register, purchase, add items to the current order, create and delete books (if he has administrator privileges). Now let's see what happens when users click on the "Fantasy" category to see what books are in that category.
We will have a specific controller to handle all book-related operations (view, edit, create, etc.). In this example, I named the controller books_controller.php. We also have a model (such as book_model.php) to handle the data and the logic associated with the book items in the store. Finally, we have some views to show the data, a list of books, a page to edit a book, and so on.
The following illustration shows how a user's view request is handled: the controller (books_controller.php) receives the user's request as an HTTP GET or post [1] (we can also have a host controller, such as index.php, to receive the request, Then it calls ooks_controller.php again)
[2] The controller examines the request and the corresponding parameters, and then calls the model (book_model.php), requesting the model to return to the Fantasy class book. The model is responsible for fetching information from the database [3], if necessary it can add filtering and logic, and then return to the book list.
The controller uses the appropriate view to present the data to the user [6-7], and if the user also chooses a specific skin, the corresponding views file will be selected and so on.
What are the benefits of MVC?
One of the most obvious benefits of using MVC is that it separates the view presentation from the application logic clearly.
Support for different users and different device types has been a common problem for the moment. A request from a desktop computer and a mobile phone should have a different view. The model returns exactly the same data, but the difference is that the controller chooses which view file to use to present the data (we can think of it as a different template).
Apart from separating the view from the business logic, the separation of MVC also reduces the difficulty of large-scale application design. The code is also more structured and therefore easier to maintain, test, and reuse.
but why frame?
When you use a framework, the basic structure of MVC is already included, and you only need to augment these structures to place your files in the appropriate directory in the MVC pattern. It also offers a number of ready-to-test and fully tested functions.
Take the example of CakePHP's most MVC framework. Once you've installed it, you'll find it contains three main directories:
* app/* cake/* vendors/
The app folder is where you place your application files. This is where you open the app.
The cake folder is where cakephp files are stored and where they are developed (the important function of the framework is inside)
The Vendors folder is the location for storing the required third-party PHP library files.
Your working folder (app folder) has the following structure:
* app/config/controllers/locale/models/plugins/tests/ tmp/vendors/o views/o webroot/
Now you need to put your controller in the controllers directory, your model is placed in the models directory, and the view file is in the views directory.
Once you're familiar with the framework, you'll know where to start when you need to modify and create the code. This kind of file organization way makes maintenance easy on a lot.
take the framework as an exampleBecause this tutorial is not intended to teach you how to use cakephp to make an application, we just use it to show the demo code of the model, view, and controller, and make a comment on the benefits of using the MVC framework. These codes are simplified and are not suitable for practical applications.
We had an online bookstore before, and a curious user wanted to see a list of all the books under the fantasy category. We said the controller will receive the request and then coordinate the operation of the controller.
So when the user clicks, the browser requests the following URLs:
Www.ourstore.com/books/list/fantasy
CakePHP's URL address form is/controller/operation/parameter 1/Parameter 2. Here the operation is called within the controller to call the function. Before the old URL URLs are
Www.ourstore.com/books_controller.php?action=list&category=fantasy
Controller
Using the cakephp framework, our controller looks like this:
<?phpClass Bookscontroller extends AppController {Function List ($category) { $this->set (' books ', $this->book->findallbycategory ($category));}function Add () {...}function Delete () {...}... ... } ?>
It's simple, isn't it. This controller will be saved as books_controller.php and placed in the/app/controllers directory. It contains a list function to perform the actions in our example, and it can also contain other books-related actions (like adding new books, deleting new books)
The framework gives us a lot of content, listing all books in just one line of code. We have a base class defined in the basic controller behavior and we have inherited it. (AppController inherited from Controller)
In the list operation, all we need to do is call the model to get the data and then select the appropriate view file to present the data to the user. Let us explain the process below.
This->book is our model, and the following code
$this->book->findallbycategory ($category)
is to tell the model to return the list of books under the selected category
The following set method
$this->set (' books ', $this->book->findallbycategory ($category));
is to tell the controller to transfer the data to the view. It transmits the data returned by the model to the view with a variable of books, and then the variable is accessible in the view.
Now we need to render the view, and if you are using the default view, CakePHP will help you do it automatically. If you need to use a different view, you need to use the Render method to specifically declare
Model
The model is very simple.
<?phpClass Book extends Appmodel {}?>
Why is it empty? Because it inherits some of the necessary functionality from the underlying class, we just need to follow CakePHP's naming conventions and the framework will automatically help you with other things. Like what. By name, CakePHP knows that this is the model used in Bookscontroller. It then automatically accesses a data table called books in the database.
This definition, our book model has the ability to read, delete, and save data from the database.
This code should be saved as books.php and placed under the/app/models file.
View
What we need to do now is to create a view (at least one) for the list operation. This view will use HTML code and also contain some PHP code to traverse the books array provided by the model.
<table> <tr> <th>Title</th> <th>Author</th> <th>Price</th> </tr ><?php foreach ($books as $book):?> <tr> <td> <?php echo $book [' book ' [' title '];?> </td> &L T;td> <?php echo $book [' book '] [' author '],?> </td> <td> <?php echo $book [' book '] [' price '];?> </td> </tr> <?php Endforeach;?></table>
As we have seen, the view file does not generate a finished page, it is just a piece of HTML code. This is because cakephp provides a way to define the layout of the page, and the view is inserted into the layout. When creating these HTML fragments, the framework also provides helper objects to help us accomplish common tasks (inserting forms, links, Ajax, or JavaScript) We save this default view as LIST.CTP (list is the name of the action, and CTP refers to the cake template) and then place it under/app/views/books (in the books directory because it is the operation of the book Controller).
With the help of cakephp, these three parts have been completed.
Conclusion
We have learned about the most commonly used architectural pattern MVC today, and we need to be aware that when we refer to the schema in the programming world, we are referring to a flexible architecture that can be used to solve the problems in the hands. We will find that the actual use will bring changes to the structure we see. But most importantly, this model will help us to differentiate the functions of each part of the program, facilitate program maintenance, code reuse, and testing.
We've seen the benefits of using the MVC framework, which provides us with a basic MVC skeleton, as well as many useful features that improve our efficiency and make the development process easier.

A beginner's Guide to MVC

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.