


PHP development framework Yii Framework tutorial (2) Yii Web application basics
With the previous "Hello, World", Yii application development seems to be easy, don't jump to conclusions so quickly:-), I remember when I first started using MFC development many years ago, after writing the first Hello, World, I still I feel like I don’t know where to start, and I don’t know how to start writing MFC applications. This is because MFC provides a large number of class libraries. If you don’t know about the MFC application framework and the main class libraries it provides in advance, you basically won’t be able to write applications and learn. Yii Framework, you also need to first understand the main components and some commonly used classes that make up Yii applications.
In the previous tutorial, I said that Yii uses MVC (Model-View-Controller), and introduced the entry script and the main application class CWebApplication class. An instance of an application class is created as an object (Singleton) by the entry script. This application singleton object can be accessed from anywhere via Yii::app().
Main application instance (CWebApplication)
By default, the application is an instance of CWebApplication. To customize it, we usually need to provide a configuration file (or array) to initialize its property values when creating the application instance. Another way to customize your application is to extend CWebApplication.
Configuration is an array of key-value pairs. Each key represents the name of a property in the application instance, and each value is the initial value of the corresponding property. For example, the following configuration sets the application's name and defaultController properties.
array( 'name'=>'Yii Framework', 'defaultController'=>'site', )
We usually save these configurations in a separate PHP script (e.g.protected/config/main.php). In the script, we return this configuration array via:
return array(...); To apply this configuration, we pass the name of the configuration file as a parameter to the application's constructor, or like below This is passed to Yii::createWebApplication(). This is usually done in the entry script:
$app=Yii::createWebApplication($configFile);Application component
The functionality of the application can be easily customized or enhanced through its flexible component structure . The application manages a series of application components, each component implements a specific function. For example, the application parses requests from the user with the help of CUrlManager and CHttpRequest.
By configuring the components attribute of the application, we can customize any component class and its attribute values used in the application. For example, we can configure the application's CMemCache component so that it can use multiple memcache servers for caching:
array( ...... 'components'=>array( ...... 'cache'=>array( 'class'=>'CMemCache', 'servers'=>array( array('host'=>'server1', 'port'=>11211, 'weight'=>60), array('host'=>'server2', 'port'=>11211, 'weight'=>40), ), ), ),
) As shown above, we added the cache element to the components array. The cache element indicates that the class of this component is CMemCache, and its servers attribute should be initialized accordingly.
To access an application component, use Yii::app()->ComponentID, where ComponentID refers to the component ID (for example, Yii::app()->cache).
App components can be disabled by setting enabled to false in their configuration. Null will be returned when we access a disabled component.
Life cycle of CWebApplication
When processing user requests, the application will go through the following declaration cycle:
Pre-initialize the application through CApplication::preinit();
Set the autoloader and error handling of classes;
Register core class components;
Load application configuration;
Initialize the application through CApplication::init():
Register application behavior;
Load static application components;
Trigger onBeginRequest event;
Process user requests:
Parse users Request;
Create controller;
Run controller;
Trigger onEndRequest event.
CController Control Class
A controller is an instance of CController or its subclass. It is created by the application when requested by the user. When a controller runs, it performs the requested action, which typically introduces the necessary models and renders the corresponding views. The simplest form of an action is a controller class method whose name starts with action.
Controllers usually have a default action. When the user's request does not specify an action to be performed, the default action will be performed. By default, the default action name is index. It can be modified by setting CController::defaultAction.
The following is the simplest code required for a controller class. Since this controller has no actions defined, requests to it will throw an exception.
class SiteController extends CController { }
Routing
The basic format of the URL for users to access web pages is /index.php?r=XController/YAction, which corresponds to XController.php in the controllers subdirectory of the protected directory with code Define the YAction method of class XController. For example, the route post/edit represents the PostController and its edit action. By default, the URL http://hostname/index.php?r=post/edit requests this controller and action. Model (CModel class) A model is an instance of CModel or one of its subclasses. Models are used to hold data and its related business logic.
Yii implements two types of models: form model and Active Record. Both inherit from the same base class CModel.
The form model is an instance of CFormModel. The form model is used to hold data obtained from the user's input. This data is often acquired, used, and then discarded. For example, in a login page, we can use the form model to represent the username and password information provided by the end user. For more details, please refer to the usage form.
Active Record (AR) is a design pattern for abstracting database access in an object-oriented style. Each AR object is an instance of CActiveRecord or one of its subclasses. Represents a row in the data table. The fields in the row correspond to properties in the AR object.
ViewView
A view is a PHP script that contains the main user interaction elements. He can contain PHP statements, but we recommend that these statements do not change the data model, and it is best to maintain its simplicity (simply as a view). In order to achieve separation of logic and interface, large sections of logic should be placed in the controller or model rather than in the view.
By analogy with Windows applications, View is similar to the Form class of Windows applications, in which controls are used to define the UI. The controls correspond to the Yii framework and become CWidget, which is a component mainly used to represent data. Small objects Usually embedded in a view to produce some complex and independent user interface. For example, a calendar widget can be used to render a complex calendar interface. Widgets make the user interface more reusable.
Masterpage, which is similar to Asp.Net, is called Layout in Yii.
A layout is a special view file used to decorate a view. It usually contains a common part of the view in the user interface. For example: the layout can include the header and footer parts, and then embed the content in between.
......header here......
......footer here......$content stores the content view Rendering results.
When using render(), layout is applied implicitly. The view script protected/views/layouts/main.php is the default layout file. This can be changed by changing CWebApplication::layout or CWebApplication: :layout to customize. To render a view without a layout, call renderPartial() .
The above introduces several important components of the Yii application. You can refer to the "Hello, World" example, and the file structure of the Yii application also has a default definition. The following is the default directory structure of the application:
Before formally developing Yii applications, first take a rough look at the class library provided by Yii http://www.yiiframework.com/doc/api/, which is listed in the figure below Yii Package definition of the class library provided by Framework:
Only by first understanding the main components of Yii applications and the main functions supported by each class package can we use Yii more flexibly in the future. to develop web applications.
The above is the content of the PHP development framework Yii Framework tutorial (2) Yii Web application basics. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Use the FastAPI framework to build international Web applications. FastAPI is a high-performance Python Web framework that combines Python type annotations and high-performance asynchronous support to make developing Web applications simpler, faster, and more reliable. When building an international Web application, FastAPI provides convenient tools and concepts that can make the application easily support multiple languages. Below I will give a specific code example to introduce how to use the FastAPI framework to build

How does PHP8 improve the performance of web applications through JIT compilation? With the continuous development of Web applications and the increase in demand, improving the performance of Web applications has become one of the focuses of developers. As a commonly used server-side scripting language, PHP has always been loved by developers. The JIT (just-in-time compilation) compiler was introduced in PHP8, providing developers with a new performance optimization solution. This article will discuss in detail how PHP8 can improve the performance of web applications through JIT compilation, and provide specific code examples.

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

With the development of the Internet and the popularity of applications, the demand for Web applications has also continued to grow. In order to meet the needs of a large number of users, traditional web applications often face performance bottlenecks and scalability issues. In response to these problems, microservice architecture has gradually become a trend and solution for web application development. In the microservice architecture, the Beego framework has become the first choice of many developers. Its efficiency, flexibility, and ease of use are deeply loved by developers. This article will introduce the use of Beego framework to develop web applications with microservice architecture.

With the popularity and development of the Internet, Web applications have become an indispensable and important part of today's society. For large-scale web applications, an efficient, scalable, and maintainable framework is essential. Under such circumstances, Django has become a popular web framework because it adopts many best practices to help developers quickly build high-quality web applications. In this article, we will introduce some best practices for building large-scale web applications using Django.
