


Yii Framework Official Tutorial Supplement 6 - Basic Knowledge: Application, Components, Configuration, Life Cycle
#Application refers to the execution context in request processing. Its main task is to analyze user requests and dispatch them to the appropriate controller for further processing. It also serves as a service center, maintaining application-level configurations. In view of this, the application is also called the front-end controller.
The application is created as a singleton object by the entry script. This application singleton object can be accessed from anywhere via Yii::app().
1. Application configuration
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 add the configuration file The name is passed as a parameter to the application's constructor, or to Yii::createWebApplication() as follows. This is usually done in the entry script:
$app=Yii::createWebApplication($configFile);
Tip: If the application configuration Very complex, we can split it into several files, each file returns a part of the configuration array. Then, in the main configuration file, we call PHP's include() to include the remaining configuration files and merge them into a complete configuration array.
2. Application base directory
The application base directory refers to the root directory that contains all security-sensitive PHP scripts and data. By default, it is a subdirectory named protected located in the directory containing the entry script. It can be customized by setting the basePath attribute in the application configuration.
Contents in the application base directory should be protected from direct access by website visitors. For the Apache HTTP server, this is easily accomplished by placing a .htaccess file in the base directory. The content of .htaccess is as follows:
deny from all
3. Application components
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 property 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 in 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.
Tips: By default, application components will be created on demand. This means that if an application component is not accessed in a user request, it may not be created at all. Therefore, if an application is configured with many components, its overall performance may not degrade. Some application components (such as CLogRouter) may need to be created regardless of whether they are accessed. To do this, list its ID in the preload attribute of your application.
4. Core application components
Yii predefines a series of core application components to provide functions used in common web applications. For example, the request component is used to parse user requests and provide information such as URL, cookies, etc. By configuring the properties of these core components, we can modify Yii's default behavior in almost all aspects.
Below we list the core components predefined by CWebApplication.
assetManager: CAssetManager - manages the release of private resource files.
authManager: CAuthManager - Manages role-based access control (RBAC).
cache: CCache - Provides data caching functionality. Note that you must specify the actual class (eg CMemCache, CDbCache). Otherwise, NULL will be returned when you access this component.
clientScript: CClientScript - manages client scripts (javascripts and CSS).
coreMessages: CPhpMessageSource - Provides translation of core messages used by the Yii framework.
db: CDbConnection - Provides database connection. Note that to use this component you must configure its connectionString property.
errorHandler: CErrorHandler - Handles uncaught PHP errors and exceptions.
format: CFormatter - formatted numerical display. This feature is available starting with version 1.1.0.
messages: CPhpMessageSource - Provides message translations used in Yii applications.
request: CHttpRequest - Provides information about the user's request.
securityManager: CSecurityManager - Provides security-related services such as hashing and encryption.
session: CHttpSession - Provides session-related functions.
statePersister: CStatePersister - Provides global state persistence methods.
urlManager: CUrlManager - Provides URL parsing and creation related functions
user: CWebUser - Provides identification information of the current user.
themeManager: CThemeManager - manages themes.
5. Application life cycle
When processing user requests, the application will go through the following lifecycle:
Pass CApplication::preinit() pre-initializes the application;
Set the automatic loader and error handling of the class;
Register core class components;
Load application configuration;
Initialize the application through CApplication::init():
Register application behavior;
Load static application components;
- Parse user requests;
- Create controller;
- Run the controller;

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

Yii framework middleware: providing multiple data storage support for applications Introduction Middleware (middleware) is an important concept in the Yii framework, which provides multiple data storage support for applications. Middleware acts like a filter, inserting custom code between an application's requests and responses. Through middleware, we can process, verify, filter requests, and then pass the processed results to the next middleware or final handler. Middleware in the Yii framework is very easy to use

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,

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

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.

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

In modern web application development, debugging tools are indispensable. They help developers find and solve various problems with their applications. As a popular web application framework, the Yii framework naturally provides some debugging tools. This article will focus on the debugging tools in the Yii framework and discuss how they help us analyze and debug applications. GiiGii is a code generator for the Yii framework. It can automatically generate code for Yii applications, such as models, controllers, views, etc. Using Gii,

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.

Methods for referencing CSS in the Yii framework: 1. Inline style, writing the CSS style directly on the HTML element in the view file; 2. Internal style sheet, using the style tag in the head tag of the view file to define the CSS style; 3. For external style sheets, create a separate CSS file and reference it using the link tag in the view file.
