国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 PHP開發(fā) Yii Framework Analysis (3) - Class Loading Mechanism and Management, Configuration, Access and Creation of Application Components

Yii Framework Analysis (3) - Class Loading Mechanism and Management, Configuration, Access and Creation of Application Components

Dec 27, 2016 am 11:11 AM
yii framework

The entry script of the Yii application references the Yii class. The definition of the Yii class:

class Yii extends YiiBase
{
}

In the application created by yiic, the Yii class is just the "vest" of the YiiBase class. We can also customize our own according to our needs. Yii category.

Yii (i.e. YiiBase) is a "helper class" that provides static and global access to the entire application.

Several static members of the Yii class:
$_aliases: stores the real paths corresponding to system aliases
$_imports:
$_classes:
$_includePaths php include paths
$_app: CWebApplication object, accessed through Yii::app()
$_logger: System log object
$_app object is created by Yii::createWebApplication() method.

Class automatic loading

Yii is based on the autoload mechanism of php5 to provide the automatic loading function of classes. The automatic loader is the static method autoload() of the YiiBase class.

When the program uses new to create an object or access a static member of a class, PHP passes the class name to the class loader, and the class loader completes the include of the class file.

The autoload mechanism implements the "on-demand import" of classes, which means that the system includes the class file only when it accesses the class.

The static member $_coreClasses of the YiiBase class pre-stores Yii's own core class name and the corresponding class file path. Classes used in other Yii applications can be imported using Yii::import(). Yii::import() stores the single class and corresponding class files in $_classes, and adds the path represented by the * wildcard character to php include_path. . Class files or directories imported by Yii::import() are recorded in $_imports to avoid multiple imports.

/* Yii::import()
* $alias: 要導入的類名或路徑
* $forceInclude false:只導入不include類文件,true則導入并include類文件
*/
public static function import($alias,$forceInclude=false)
{
    // 先判斷$alias是否存在于YiiBase::$_imports[] 中,已存在的直接return, 避免重復import。
    if(isset(self::$_imports[$alias])) // previously imported
        return self::$_imports[$alias];
    // $alias類已定義,記入$_imports[],直接返回
    if(class_exists($alias,false) || interface_exists($alias,false))
        return self::$_imports[$alias]=$alias;
    // 已定義于$_coreClasses[]的類,或名字中不含.的類,記入$_imports[],直接返回
    if(isset(self::$_coreClasses[$alias]) || ($pos=strrpos($alias,’.'))===false) // a simple class name
    {
        self::$_imports[$alias]=$alias;
        if($forceInclude)
        {
            if(isset(self::$_coreClasses[$alias])) // a core class
                require(YII_PATH.self::$_coreClasses[$alias]);
            else
                require($alias.’.php’);
        }
        return $alias;
    }
    // 產(chǎn)生一個變量 $className,為$alias最后一個.后面的部分
    // 這樣的:’x.y.ClassNamer’
    // $className不等于 ‘*’, 并且ClassNamer類已定義的,????? ClassNamer’ 記入 $_imports[],直接返回
    if(($className=(string)substr($alias,$pos+1))!==’*’ 
            && (class_exists($className,false) || interface_exists($className,false)))
        return self::$_imports[$alias]=$className;
    // $alias里含有別名,并轉(zhuǎn)換真實路徑成功
    if(($path=self::getPathOfAlias($alias))!==false)
    {
        // 不是以*結(jié)尾的路徑(單類)
        if($className!==’*')
        {
            self::$_imports[$alias]=$className;
            if($forceInclude)
                require($path.’.php’);
            else
                // 類名與真實路徑記入$_classes數(shù)組
                self::$_classes[$className]=$path.’.php’;
            return $className;
        }
        // $alias是’system.web.*’這樣的已*結(jié)尾的路徑,將路徑加到include_path中
        else // a directory
        {
            if(self::$_includePaths===null)
            {
                self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
                if(($pos=array_search(‘.’,self::$_includePaths,true))!==false)
                    unset(self::$_includePaths[$pos]);
             }
            array_unshift(self::$_includePaths,$path);
            set_include_path(‘.’.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths));
            return self::$_imports[$alias]=$path;
         }
    }
    else
        throw new CException(Yii::t(‘yii’,'Alias “{alias}” is invalid. Make sure it points to an existing directory or file.’,array(‘{alias}’=>$alias)));
}

Then take a look at the processing of the YiiBase::autoload() function:

public static function autoload($className)
{
    // $_coreClasses中配置好的類直接引入
    if(isset(self::$_coreClasses[$className]))
        include(YII_PATH.self::$_coreClasses[$className]);
    // $_classes 中登記的單類直接引入
    else if(isset(self::$_classes[$className]))
        include(self::$_classes[$className]);
    else
    {
        // 其他的認為文件路徑以記入 include_path 里,以$className.’.php’直接引入
        include($className.’.php’);
        return class_exists($className,false) || interface_exists($className,false);
    }
    return true;
}

The classes or paths in the import item in the system configuration file will be automatically imported during script startup. For classes that need to be imported into individual classes in user applications, the Yii::import() statement can be added before the class definition.

Application component management

As mentioned earlier, Yii's CComponent class provides access interfaces to component properties, events, and behaviors, and CComponent's subclass CModule also provides application components. management.

The application component must be an instance of the IApplicationComponent interface and needs to implement the init() and getIsInitialized() methods of the interface. init() will be automatically called after applying component initialization parameters.

Yii's own functional modules are provided through application components, such as the common Yii::app()->user, Yii::app()->request, etc. Users can also define application components.

As the parent class of the Yii::app() object (CWebApplication), CModule provides complete component life cycle management, including component creation, initialization, object storage, etc.

Each application component is identified by a string name and accessed through the __get() method of the CModule class.

The $_components[] member of the CModule class stores the object instance of the application component ($name => $object), and $_componentConfig[] stores the class name and initialization parameters of the application component.

When using an application component, first set the class name and initialization parameters of the component in $_componentConfig. When accessing the component for the first time, CModule will automatically create an application component object instance and initialize the given parameters. Then the init() method of the application component is called.

Yii::app() object's class CWebApplication and its parent class CApplication are pre-configured with application components used by the system itself: urlManager, request, session, assetManager, user, themeManager, authManager, clientScript, coreMessages, db, messages, errorHandler, securityManager, statePersister.

We can modify the parameters of the system application components or configure new application components in the components project of the system configuration file.

CModule is not responsible for the creation of application component instances, but is completed by the Yii::createComponent() static method.

The parameter $config of createComponent() can be a string of class name or an array storing class name and initialization parameters.

Configuration of application components

The configuration of application components is stored in the components item in the system $config variable (config/main.php):

// application components
‘components’=>array(
    ‘log’=>array(
        ‘class’=>’CLogRouter’,
        ‘routes’=>array(
            array(
                ‘class’=>’CFileLogRoute’,
                ‘levels’=>’error, warning’,
            ),
         ),
    ),
    ‘user’=>array(
    // enable cookie-based authentication
        ‘a(chǎn)llowAutoLogin’=>true,
    ),
),

$config The components items are processed in the constructor of CApplication:

$this->configure($config);

The processing of the configure() function is very simple:

public function configure($config)
{
    if(is_array($config))
    {
        foreach($config as $key=>$value)
            $this->$key=$value;
    }
}

Each item in $config is passed as an attribute to the setXXX() attribute setting method of the $_app object, where the 'components' item is processed by setComponents(), the parent class of CModule in CWebApplication.

setComponents() stores the class name and initialization parameters in the 'components' item into $_componentConfig[]:

public function setComponents($components)
{
    // $config 里的’components’每一項
    foreach($components as $id=>$component)
    {
        if($component instanceof IApplicationComponent)
            $this->setComponent($id,$component);
        // $_componentConfig里已經(jīng)存在配置,合并$component
        else if(isset($this->_componentConfig[$id]))
            $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
        // 在$_componentConfig里新建項目
        else
            $this->_componentConfig[$id]=$component;
    }
}

Access to application components

CModule類重載了CComponent的__get()方法,優(yōu)先訪問應(yīng)用組件對象。

public function __get($name)
{
    if($this->hasComponent($name))
        return $this->getComponent($name);
    else
        return parent::__get($name);
}

hasComponent() 判斷$_components[]中是否已存在組件實例,或$_componentConfig[]中存在組件配置信息。

public function hasComponent($id)
{
    return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
}

getComponent() 判斷組件實例已經(jīng)存在于$_components[]中,則直接返回對象。
否則根據(jù)$_componentConfig[]里的組件配置數(shù)據(jù)調(diào)用 Yii::createComponent() 來創(chuàng)建組件,并將對象存入$_components[]中然后返回。

public function getComponent($id,$createIfNull=true)
{
    if(isset($this->_components[$id]))
        return $this->_components[$id];
    else if(isset($this->_componentConfig[$id]) && $createIfNull)
    {
        $config=$this->_componentConfig[$id];
        unset($this->_componentConfig[$id]);
        if(!isset($config['enabled']) || $config['enabled'])
        {
            Yii::trace(“Loading \”$id\” application component”,’system.web.CModule’);
            unset($config['enabled']);
            $component=Yii::createComponent($config);
            $component->init();
            return $this->_components[$id]=$component;
        }
    }
}

應(yīng)用組件的創(chuàng)建

Yii::createComponent() 來完成應(yīng)用組件的創(chuàng)建

public static function createComponent($config)
{
    if(is_string($config))
    {
        $type=$config;
        $config=array();
    }
    else if(isset($config['class']))
    {
        $type=$config['class'];
        unset($config['class']);
    }
    else
        throw new CException(Yii::t(‘yii’,'Object configuration must be an array containing a “class” element.’));
 
    if(!class_exists($type,false))
        $type=Yii::import($type,true);
 
    if(($n=func_num_args())>1)
    {
        $args=func_get_args();
        if($n===2)
            $object=new $type($args[1]);
        else if($n===3)
            $object=new $type($args[1],$args[2]);
        else if($n===4)
            $object=new $type($args[1],$args[2],$args[3]);
        else
        {
            unset($args[0]);
            $class=new ReflectionClass($type);
            // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
            // $object=$class->newInstanceArgs($args);
            $object=call_user_func_array(array($class,’newInstance’),$args);
        }
    }
    else
        $object=new $type;
 
    foreach($config as $key=>$value)
    $object->$key=$value;
 
    return $object;
}

?以上就是Yii框架分析(三)——類加載機制及應(yīng)用組件的管理、配置、訪問、創(chuàng)建的內(nèi)容,更多相關(guān)內(nèi)容請關(guān)注PHP中文網(wǎng)(www.miracleart.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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

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)

Hot Topics

PHP Tutorial
1502
276
Yii framework middleware: providing multiple data storage support for applications Yii framework middleware: providing multiple data storage support for applications Jul 28, 2023 pm 12:43 PM

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

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 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,

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

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

Debugging Tools in the Yii Framework: Profiling and Debugging Applications Debugging Tools in the Yii Framework: Profiling and Debugging Applications Jun 21, 2023 pm 06:18 PM

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,

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 Interview Questions: Ace Your PHP Framework Interview Yii Interview Questions: Ace Your PHP Framework Interview Apr 06, 2025 am 12:20 AM

When preparing for an interview with Yii framework, you need to know the following key knowledge points: 1. MVC architecture: Understand the collaborative work of models, views and controllers. 2. ActiveRecord: Master the use of ORM tools and simplify database operations. 3. Widgets and Helpers: Familiar with built-in components and helper functions, and quickly build the user interface. Mastering these core concepts and best practices will help you stand out in the interview.

See all articles