Yii Framework Official Tutorial Supplement 6 - Basic Knowledge: Application, Components, Configuration, Life Cycle

黄舟
Release: 2023-03-05 17:32:01
Original
1356 people have browsed it



#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',
)
Copy after login

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(...);
Copy after login

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);
Copy after login

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
Copy after login

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),
            ),
        ),
    ),
)
Copy after login

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:

  1. Pass CApplication::preinit() pre-initializes the application;

  2. Set the automatic loader and error handling of the class;

  3. Register core class components;

  4. Load application configuration;

  5. Initialize the application through CApplication::init():

  • Register application behavior;

  • Load static application components;

  • ##Trigger onBeginRequest event;

  • Processing user requests:

    • Parse user requests;

    • Create controller;

    • Run the controller;

  • Trigger the onEndRequest event.

  • Yii Framework Official Tutorial Supplement 6 - Basic Knowledge: Application, Components, Configuration, Life Cycle

    The above is the Yii Framework official tutorial supplement 6 - basic knowledge: application, components, configuration, life cycle content, and more related content Please pay attention to the PHP Chinese website (www.php.cn)!


    source: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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!