Yii Framework official guide series 15-Basic Knowledge: best MVC practices

Source: Internet
Author: User
Although the model-view-controller (MVC) is widely known to almost every Web developer, the rational use of MVC in actual application development still bothers many people. The core idea behind MC is code reusability and logic and...



Although the model-view-controller (MVC) is widely known to almost every Web developer, the rational use of MVC in actual application development still bothers many people. The core idea behind MC isCode reusability and separation of logic and view. This section describes how to better use MVC to develop applications when using the Yii Framework.

For better explanation, we assume that the Web application contains the following sub-applications:

  • Front-end: Public website interface for end users;

  • Backend: provides the management function for managing the entire website application, which can be accessed and used by administrators only;

  • Console: an application that contains console commands that can be run in the terminal window;

  • Web API: Provides interfaces for third parties to interact with the application.

These sub-applications may be implemented in the form of modules or Yii applications that share code with other sub-applications.

1. model

Models represent the underlying data structure of a Web application. Models are often shared among different sub-applications of a Web application. For example,LoginFormModel may be used by both the front end and the back end of an application;NewsModel may be used by the console commands, Web APIs, and the front/back end of an application. Therefore, models

  • Shocould contain properties to represent specific data;

  • Shocould contain business logic (e.g. validation rules) to ensure the represented data fulfills the design requirement;

  • May contain code for manipulating data. For example,SearchFormModel, besides representing the search input data, may containsearchMethod to implement the actual search.

Sometimes, following the last rule above may make a model very fat, containing too much code in a single class. it may also make the model hard to maintain if the code it contains serves different purposes. for example,NewsModel may contain a method namedgetLatestNewsWhich is only used by the front end; it may also contain a method namedgetDeletedNewsWhich is only used by the back end. This may be fine for an application of small to medium size. For large applications, the following strategy may be used to make models more maintainable:

  • DefineNewsBaseModel class which only contains code shared by different sub-applications (e.g. front end, back end );

  • In each sub-application, defineNewsModel by extending fromNewsBase. Place all of the code that is specific to the sub-application in thisNewsModel.

So, if we were to employ this strategy in our abve example, we wocould addNewsModel in the front end application that contains onlygetLatestNewsMethod, and we wocould add anotherNewsModel in the back end application, which contains onlygetDeletedNewsMethod.

In general, models shoshould not contain logic that deals directly with end users. More specifically, models

  • Shocould not use$_GET,$_POST, Or other similar variables that are directly tied to the end-user request. remember that a model may be used by a totally different sub-application (e.g. unit test, Web API) that may not use these variables to represent user requests. these variables pertaining to the user request shocould be handled by the Controller.

  • Shoshould avoid embedding HTML or other presentational code. because presentational code varies according to end user requirements (e.g. front end and back end may show the detail of a news in completely different formats), it is better taken care of by views.

2. View

Views are responsible for presenting models in the format that end users desire. In general, views

  • Shoshould mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data;

  • Shocould avoid containing code that performs explicit DB queries. Such code is better placed in models.

  • Shoshould avoid direct access$_GET,$_POST, Or other similar variables that represent the end user request. this is the controller's job. the view shoshould be focused on the display and layout of the data provided to it by the controller and/or model, but not attempting to access request variables or the database directly.

  • May access properties and methods of controllers and models directly. However, this shocould be done only for the purpose of presentation.

Views can be reused in different ways:

  • Layout: common presentational areas (e.g. page header, footer) can be put in a layout view.

  • Partial views: use partial views (views that are not decorated by layouts) to reuse fragments of presentational code. For example, we use_form.phpPartial view to render the model input form that is used in both model creation and updating pages.

  • Widgets: if a lot of logic is needed to present a partial view, the partial view can be turned into a widget whose class file is the best place to contain this logic. for widgets that generate a lot of HTML markup, it is best to use view files specific to the widget to contain the markup.

  • Helper classes: in views we often need some code snippets to do tiny tasks such as formatting data or generating HTML tags. rather than placing this code directly into the view files, a better approach is to place all of these code snippets in a view helper class. then, just use the helper class in your view files. yii provides an example of this approach. yii has a powerful CHtml helper class that can produce commonly used HTML code. helper classes may be put in an autoloadable directory so that they can be used without explicit class definition Sion.

3. Controller

Controllers are the glue that binds models, views and other components together into a runnable application. Controllers are responsible for dealing directly with end user requests. Therefore, controllers

  • May access$_GET,$_POSTAnd other PHP variables that represent user requests;

  • May create model instances and manage their life cycles. For example, in a typical model update action, the controller may first create the model instance; then populate the model with the user input from$_POST; After saving the model successfully, the controller may redirect the user browser to the model detail page. Note that the actual implementation of saving a model shocould be located in the model instead of the controller.

  • Shocould avoid containing embedded SQL statements, which are better kept in models.

  • Shocould avoid containing any HTML or any other presentational markup. This is better kept in views.

In a well-designed MVC application, controllers are often very thin, containing probably only a few dozen lines of code; while models are very fat, containing most of the code responsible for representing and manipulating the data. this is because the data structure and business logic represented by models is typically very specific to the specified application, and needs to be heavily customized to meet the specific application requirements; while controller logic often follows a similar pattern processing SS applications and therefore may well be simplified by the underlying framework or the base classes.

The above is the Yii Framework official guide series 15-basic knowledge: Content of best MVC practices. For more information, please follow the PHP Chinese network (www.php1.cn )!

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.