Deep understanding of the MVC architecture

Source: Internet
Author: User
Tags yii

Mvc

MVC is a design pattern, that is, a solution to the problem of the method and ideas, was proposed in the 80 's, it has been quite a history. The meaning of MVC is to instruct developers to decouple data from performance, and to improve the reusability of code, especially part of the model.

MVC is not only in web design, but also a common method in desktop program development. There has been a history of the advent of MVC. Remember when I first learned about MVC, it was in MFC in Microsoft Visual C + +. At that time young ignorance, think is MFC unique things. Later on with the continuous study, only to find their innocence. So, the more you learn, the more you feel ignorant. The more you feel ignorant, the more you know awe and humility. From this point of view, students, it is best not to despise the humble people.

There is a such a joke, said one day a June in the Circle party, a friend introduced another person B June know each other. It's normal and common in a party situation. So ab June chatted a little bit. According to the habits of the people, a June asked, "Where is Mr. Gao?" ”。 b June Only said a sentence, "not a job, stir fry stocks." "Oh, the original is the stock." "A June thought, although did not feel anything wrong, but the psychology thought b a bit low, just did not you said, also did not show out." After a period of time, a chance, found that the original B is a domestic listed company's two shareholders, the net worth over billion. People did not say panic, is indeed the stock of ...

As far as we are, we are talking about the point. MVC is a three-word abbreviation: Model, View, Controller. MVC is a design pattern, and almost all web development frameworks are built on the MVC pattern. Of course, in recent years there have been new design patterns such as MVP and MVVM. But MVC is still mainstream in terms of the sophistication of technology and the extent to which it is used.

Yii is a web framework, from the Web development of the Division of labor, Yii development work, bear the back-end content more, after all, is mainly PHP development. Front-end is mainly in the HTML, JavaScript, CSS development, and then through Yii to the front-end content of the tube, such as through assets. This chapter is about MVC, mainly for the backend. The front-end MVC is strictly not part of the Yii category, and here we don't introduce too much. If you want to know the front-end MVC, look at the front-end frameworks such as Backbone.js angular.js.

Three elements of MVC

MVC is the abbreviation for a model, a view, a controller, and 3 words. Here are 3 ways to explain the three elements of MVC.

    • Model refers to data modeling, which is an abstraction of objective things. As a blog post, we may be represented as a post class, so the post class is the data object. At the same time, the blog post also has some business logic, such as publishing, recycling, comment, etc., which is generally shown as the method of the class, which is the content and scope of model. For model, it is primarily data, business logic, and business rules. In contrast, this is a relatively stable part of MVC, the general finished product will not change. The most important task in the early stages of development is the part of the model. This part is well written, the latter can be changed less, developed quickly.
    • View refers to the views, which are presented to the user interface, is the model of the specific form, but also the collection of user input places. An article that you see on a blog is a representation of a post class. The purpose of view is to provide an interface that interacts with the user. In other words, for a user, only view is visible and actionable. In fact, you won't let the user see the model, or let him manipulate the model directly. You will only let the user see what you want him to see. This is what the view does, and he tends to be a frequent part of MVC and a place where customers often ask for change. Today you may be able to present your blog in one form, and tomorrow it may become a different form of expression.
    • Contorller refers to the controller, which is primarily responsible for dealing with model and view. In other words, model and view generally do not deal directly with each other, they laosi. No action is made on the model in view, and the model does not output anything for performance, such as HTML code. These two do not work, it must be someone to do it, only controller on the. Contorller is used to decide which model to use, what to do with the model, what data to prepare for the view, and a bridge for communication in MVC.

There is no clear definition and boundaries for the three divisions in MVC. The MVC design pattern is just a guideline that allows you to describe your application in terms of model, view, controller three aspects, and through the interaction of the three, so that the application function can be normal operation.

Among them, the view part is more clear, is responsible for the display. Everything that has nothing to do with the display interface should not appear in the view. Therefore, the view generally does not appear complex judgment statement, does not appear the complex computation procedure. For PHP Web applications, there is no doubt that HTML is the main content in view. Here are a few principles of view:

    • Responsible for the display interface, HTML-based;
    • Generally there is no complex judgment statement or operation process, can have a simple loop statement, formatting statements. For example, the General blog home page of the article list, is a circular structure;
    • Never call the model's write method. That is, view only gets the data from the model, not the model directly, so we say they are laosi.
    • There is generally no code to prepare the data, such as querying the database, grouping strings into a certain format, and so on. These are generally placed inside the controller and passed to the view as a variable. In other words, the data that is used in the view is a variable that can be used directly.

For model, the most important thing is to preserve the information of things, to characterize the behavior of things and the actions that can be performed on them. For example, the Post class must have a title attribute to save the blog post header, there must be a delete operation, which is the model content. Here are a few principles about model:

    • Data, behavior and methods are the main contents of model;
    • In practice, model is the most code-intensive and logical place in MVC, because a large amount of business logic about the application is also represented here.
    • The data provided by model is the original data. That is, no code with any presentation layer. For example, it is not common to add HTML tags to the output data, which is the work of view. But model can provide structured data, array structure, queue structure, and even other model. This structure is not a presentation layer, but a representation of the data in memory.
    • Unlike output, the model's input data can be data with a presentation format. If you save an article to post, the content must contain a variety of HTML tags. Therefore, the model generally to the input data filtering, validation and normalization of preprocessing. Especially for those that need to be kept in the database, all input data must be preprocessed. Some of these preprocessing, in fact, are business logic. For example, only the editor can delete the article, this verification rule is both business logic, but also permission control. And some preprocessing, it does not belong to the business logic, for example, the text before and after the title of the space should be removed.
    • Note separate from the controller area. Model is the logic of dealing with business, controller is simply to coordinate the relationship between model and view, as long as the business-related, it should be placed in the model. A good design should be a fat model, a thin controller.

For controllers, the main response is to respond to user requests, decide what view to use, and what data needs to be prepared for display. Here are the design principles for the controller:

    • Used to process user requests. Therefore, the access code for Reqeust should be placed inside the controller, such as $_get $_post . However, it is limited to obtaining user request data and should not have any manipulation or preprocessing of the data, which should be done by models.
    • Call models's Read method, get the data, and pass it directly to the view for display. When multiple model is involved, the relevant logic should be given to the model to complete.
    • Call models's class method and write to models.
    • Call the view render function and so on, form the response to the user reqeust.
Model Design Reference

In MVC, the model row first, there is a certain hint. First, the model is the entire architecture, the code is the largest, the highest degree of reuse, but also the most embodiment of the programmer's design skill. Second, view and controller in the actual development, compared with the model, the reuse degree is not high, the logic complexity is low. It can be said that the model design is good, the whole MVC is good, application development is smooth.

Therefore, this section will take model as the core, in terms of MVC design. To be honest, MVC despite the idea of dividing the model View controller, it is not very well grasped in concrete practice. The following is the design reference, but also the individual in the actual project some of the experience and ideas, for reference only. In the specific design, you can grasp the following points:

Model should centralize data and business logic for the entire application

All business objects involved in the application should be drawn as model as possible. For example, the blog system, the article to abstract into post, comments to abstract into comment. While the related business logic, such as publishing new articles can be used post::create () , delete comments can be used Comment::d elete () . This way the entire application appears to be clear and straightforward.

The base model should be as detailed as possible

In an application, especially for large and complex applications, the relationship between the model can be complex. In the construction of the application, especially the basic model, should be from a small enough granularity to design. At this point, we should consider the adoption of inheritance, encapsulation and other measures. For example, a blog post, which typically contains several tags, is usually written on the page next to the Post field of the author, date, and so on. Logically, it is a good point to use a label as a property of post. However, if the label is attached to the post as a property such as a title, body, and so on. Then in some functions, it is difficult to achieve. For example, the customer requests that when a post contains the label "Yii, Model", you can click on "Yii", and then the system will list all the tags containing "yii" article.

In order to achieve this function, the correct design is to separate the tag into tag. In this way, post and tag are many-to-many relationships, that is, a post has multiple tags, and a tag corresponds to more than one post. This many-to-many relationship can be represented by a data table Tbl_post_tag . Next, add the post::gettags () method to post and use the tbl_post_tag table to query all the labels for the current post. At the same time, add the tag::getposts () method for tag, also through the tbl_post_tag table to query the current tag corresponding article. This provides the basis for new capabilities to meet customer requirements.

Therefore, in the model design, to be as small as possible to design the particle size. Generally, the smaller the granularity, the greater the likelihood of reuse.

Some readers may ask, since the requirements of granularity as small as possible, then the post should also be refined, the paragraph is abstracted into model? Whether it is necessary to see the needs of customers. The general situation really does not have this necessary, if this is done, is it not again in the sentence as a unit of abstraction? However, if the customer requests that the comments of the blog system are comments on the paragraph, the comments will be displayed next to the corresponding paragraphs, and even display the comments of each paragraph. Then we need to abstract the paragraph into model.

Hierarchical Design Model

From the design process, the database structure design is closely related to the model design. First, the database structure design, after the model design. When designing the database structure, the model is also being designed. In general, the most modular and granular model is the model generated by each database table, which is often an active Record.

For example, the problem of labeling, in the database stored procedures, post and tag are stored separately, and the two table fields, there is no redundancy. The Tbl_post_tag table also records their ID only, with no substance.

The two model and their fields are fully sufficient and not redundant when the data rendering view is captured and presented to the user.

So, can you say that the two model of Post and Tag is enough? Obviously not enough.

When users create articles, modify articles, and review articles, they need a form to display to collect user input. Among them, for the label collection, is generally a long strip of text box, let the user to enter multiple tags at once, and so on , and so on separated.

However, this text box does not have a field corresponding to it. There's no way we can validate and preprocess the user input for this field.

Therefore, the function of post is not enough. What if it's not enough? then add it. But it is not good to add a public $tagString the Post directly. After all, this is only a problem when using forms, and in other cases, this field is useless.

In this case, inheritance is generally used:

123456
Post$tagString... }

This way, when the Controller discovers that the user is creating, modifying, and approving an article, the Postform model can be used to render the view, while others still use post. This adds a tagstring field to collect user-entered tags when needed.

In the specific design process, because the model itself will contain a lot of code, therefore, to use this inheritance and other means to organize the code well.

Name the model method carefully

Because the model has a large amount of code and a lot of logic, there are a number of methods in a model. Still take post as an example, will involve the creation, review, release, recycling and other processes, related methods more, in the name of the intentions. Some of the approaches that may be related to names that are more approximate are:

    • Getprevpost (), previous post, for navigation
    • Getnextpost (), next post, for navigation
    • Getrelatedposts ($n = 10), get the relevant n articles for the recommended list of related articles
    • Getpostsofauthor ($n = 10), obtaining n related articles for the same author, for the author's article List
    • Getlatestposts ($n = 10), latest n article, static method, for article list or RSS output
    • Gethotestposts ($n = 10), the most popular n-article, static method, used for hot articles list
    • Getpublishposts ($n =-1), gets the published n article, static method, for the article List
    • Getdraftposts ($n =-1), get unpublished n-Articles, static methods, for author pages

Here are just a few ways to get the other post, the name is more reasonable, a look to know the meaning. And all written in getter form, can be accessed using the Read property.

Not only in the name of the model method to heart, in the name of variables, class name, method name, and so on the naming, but also to form a habit, the formation of law. Don't make a quick, random name. Otherwise, out of the mix, sooner or later.

MVC and front-end mates

From the perspective of MVC, it is developed from the development of desktop applications. In essence, this is a way of thinking and solving the problem. In practice, this is a proven and effective way. But as we say at the beginning, Yii is more focused on the backend. For Web applications, many web development frameworks, including YII, have no way of knowing what the user is doing, such as a mouse, keyboard, and so on. Web apps want to understand what users are doing, and only rely on users to send request. And the response to the mouse, keyboard, etc., can only rely on the front-end technology, such as JavaScript to achieve.

Plus, the Web browser has been more powerful over the years. Therefore, there is a new development of web application development, that is, the function from the backend to the front-end transfer.

On the front end, user actions are captured through JavaScript and processed accordingly. Or send back end to get response processing, such as through Ajax request back-end data, the implementation of non-refreshing partial page update, to the user feedback, or directly in front of the browser to process, such as the use of backbone.js, angular.js, such as the front-end framework of data binding capabilities. This makes Web applications more and more like desktop applications.

Back-end MVC is also changing for the development of the front and back. The controller's functionality becomes more of a recognition of an AJAX request or an ordinary request, and takes the corresponding view rendering according to the request. For normal requests, render the view normally, outputting the HTML. For AJAX requests, a partial render view is returned, and the HTML fragment is output. Some even output XML or JSON. The only thing in the big trend is that it's still our big model.

Deep understanding of the MVC architecture

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.