Table of Contents
Models represent the underlying data structure of a Web application. Models are often shared among different sub-applications of a Web application. For example, a
Views are responsible for presenting models in the format that end users desire. In general, views
3. 控制器
Home Backend Development PHP Tutorial Yii Framework Official Guide Series 15 - Basics: Best MVC Practices

Yii Framework Official Guide Series 15 - Basics: Best MVC Practices

Feb 13, 2017 am 09:08 AM



Although Model-View-Controller (MVC) is known to almost every web developer, how is it used in actual application development? The reasonable use of MVC still troubles many people. The core idea behind MC is the reusability of code and the separation of logic and views. In this section, we will describe 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: the public website interface for end users;
  • Backend: Provides management functions for managing the entire website application, usually only administrators can access and use;
  • Console: Can be run in a terminal window Applications that include console commands;
  • Web API: Provides an interface for third parties to interact with this application.
  • These sub-applications may be implemented in the form of modules, or they may be 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, a

LoginForm

model may be used by both the front end and the back end of an application; a News model may be used by the console commands, Web APIs, and the front/back end of an application. Therefore, models

    should contain properties to represent specific data;
  • should contain business logic (e.g. validation rules) to ensure the represented data fulfills the design requirement;
  • may contain code for manipulating data. For example, a
  • SearchForm

    model, besides representing the search input data, may contain a search method 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, a
News

model may contain a method named getLatestNews which is only used by the front end; it may also contain a method named getDeletedNews which 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:

    Define a
  • NewsBase

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

  • In each sub-application, define a
  • News

    model by extending from NewsBase. Place all of the code that is specific to the sub-application in this News model .

  • So, if we were to employ this strategy in our above example, we would add a
News

model in the front end application that contains only the getLatestNews method, and we would add another News model in the back end application, which contains only the getDeletedNews method.In general, models should not contain logic that deals directly with end users. More specifically, models

    should 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 should be handled by the Controller.

  • should 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. Views

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

    should mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data;
  • should avoid containing code that performs explicit DB queries. Such code is better placed in models.
  • should avoid direct access to
  • $_GET

    , $_POST, or other similar variables that represent the end user request. This is the controller's job. The view should 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 should 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.php partial 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 inclusion.

3. 控制器

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$_POST and 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 should be located in the model instead of the controller.

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

  • should 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 particular application, and needs to be heavily customized to meet the specific application requirements; while controller logic often follows a similar pattern across applications and therefore may well be simplified by the underlying framework or the base classes.

以上就是Yii框架官方指南系列15——基础知识:最佳MVC实践的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Yii framework in PHP How to use Yii framework in PHP Jun 27, 2023 pm 07:00 PM

With the rapid development of web applications, modern web development has become an important skill. Many frameworks and tools are available for developing efficient web applications, among which the Yii framework is a very popular framework. Yii is a high-performance, component-based PHP framework that uses the latest design patterns and technologies, provides powerful tools and components, and is ideal for building complex web applications. In this article, we will discuss how to use Yii framework to build web applications. Install Yii framework first,

Unit testing in Yii framework: ensuring code quality Unit testing in Yii framework: ensuring code quality Jun 21, 2023 am 10:57 AM

As software development becomes increasingly complex, ensuring code quality becomes increasingly important. In the Yii framework, unit testing is a very powerful tool that can ensure the correctness and stability of the code. In this article, we will take a deep dive into unit testing in the Yii framework and introduce how to use the Yii framework for unit testing. What is unit testing? Unit testing is a software testing method, usually used to test the correctness of a module, function or method. Unit tests are usually written by developers to ensure the correctness and stability of the code.

RESTful API development in Yii framework RESTful API development in Yii framework Jun 21, 2023 pm 12:34 PM

Yii is a high-performance MVC framework based on PHP. It provides a very rich set of tools and functions to support the rapid and efficient development of web applications. Among them, the RESTful API function of the Yii framework has attracted more and more attention and love from developers, because using the Yii framework can easily build high-performance and easily scalable RESTful interfaces, providing strong support for the development of web applications. . Introduction to RESTfulAPI RESTfulAPI is a

Steps to implement web page caching and page chunking using Yii framework Steps to implement web page caching and page chunking using Yii framework Jul 30, 2023 am 09:22 AM

Steps to implement web page caching and page chunking using the Yii framework Introduction: During the web development process, in order to improve the performance and user experience of the website, it is often necessary to cache and chunk the page. The Yii framework provides powerful caching and layout functions, which can help developers quickly implement web page caching and page chunking. This article will introduce how to use the Yii framework to implement web page caching and page chunking. 1. Turn on web page caching. In the Yii framework, web page caching can be turned on through the configuration file. Open the main configuration file co

Create a game guide website using Yii framework Create a game guide website using Yii framework Jun 21, 2023 pm 01:45 PM

In recent years, with the rapid development of the game industry, more and more players have begun to look for game strategies to help them pass the game. Therefore, creating a game guide website can make it easier for players to obtain game guides, and at the same time, it can also provide players with a better gaming experience. When creating such a website, we can use the Yii framework for development. The Yii framework is a web application development framework based on the PHP programming language. It has the characteristics of high efficiency, security, and strong scalability, and can help us create a game guide more quickly and efficiently.

Encrypt and decrypt sensitive data using Yii framework middleware Encrypt and decrypt sensitive data using Yii framework middleware Jul 28, 2023 pm 07:12 PM

Encrypting and decrypting sensitive data using Yii framework middleware Introduction: In modern Internet applications, privacy and data security are very important issues. To ensure that users' sensitive data is not accessible to unauthorized visitors, we need to encrypt this data. The Yii framework provides us with a simple and effective way to implement the functions of encrypting and decrypting sensitive data. In this article, we’ll cover how to achieve this using the Yii framework’s middleware. Introduction to Yii framework Yii framework is a high-performance PHP framework.

Yii Framework Middleware: Add logging and debugging capabilities to your application Yii Framework Middleware: Add logging and debugging capabilities to your application Jul 28, 2023 pm 08:49 PM

Yii framework middleware: Add logging and debugging capabilities to applications [Introduction] When developing web applications, we usually need to add some additional features to improve the performance and stability of the application. The Yii framework provides the concept of middleware that enables us to perform some additional tasks before and after the application handles the request. This article will introduce how to use the middleware function of the Yii framework to implement logging and debugging functions. [What is middleware] Middleware refers to the processing of requests and responses before and after the application processes the request.

How to use controllers to handle Ajax requests in the Yii framework How to use controllers to handle Ajax requests in the Yii framework Jul 28, 2023 pm 07:37 PM

In the Yii framework, controllers play an important role in processing requests. In addition to handling regular page requests, controllers can also be used to handle Ajax requests. This article will introduce how to handle Ajax requests in the Yii framework and provide code examples. In the Yii framework, processing Ajax requests can be carried out through the following steps: The first step is to create a controller (Controller) class. You can inherit the basic controller class yiiwebCo provided by the Yii framework

See all articles