Example of YiiBase entry class extension in the Yii Framework of PHP, yiiyiibase_PHP tutorial

Source: Internet
Author: User
Tags autoload autoloader
Yiiyiibase is an example of the YiiBase entry class extension in the Yii Framework of PHP. The YiiBase entry class extension example in the Yii Framework of PHP. yiiyiibase uses yiic. after php automatically creates an application, the initial code of the entry file is as follows: example of YiiBase entry class extension in the Yii Framework of phpchangethefollowingpaths PHP, yiiyiibase

After an application is automatically created using yiic. php, the initial code of the entry file is as follows:

<?php// change the following paths if necessary$yii=dirname(__FILE__).'/../yii/framework/yii.php';$config=dirname(__FILE__).'/protected/config/main.php';// remove the following lines when in production modedefined('YII_DEBUG') or define('YII_DEBUG',true);// specify how many levels of call stack should be shown in each log messagedefined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);require_once($yii);Yii::createWebApplication($config)->run();


The third line introduces a yii. php file, which can be found under the framework/in the yii core directory. This File defines a Yii class and inherits the YiiBase class.

The code is as follows:

require(dirname(__FILE__).'/YiiBase.php'); /** * Yii is a helper class serving common framework functionalities. * * It encapsulates {@link YiiBase} which provides the actual implementation. * By writing your own Yii class, you can customize some functionalities of YiiBase. * * @author Qiang Xue 
 
   * @package system * @since 1.0 */class Yii extends YiiBase{}
 

While

Yii::createWebApplication

This method is actually defined in the YiiBase parent class. Therefore, Yii reserves the possibility of extension for us. We only need to add the method we want to expand in yii. php, and directly use Yii: method name () for calling in the project.
To completely separate the project code from the core directory, I personally think it is better to use another yii. php in the project directory to replace yii. php in the core directory.

Here I used a more extreme method. I directly defined the yii class in the entry file and extended a global factory function instance () method. please refer to the code:

<? Php // change the following paths if necessary $ yii = dirname (_ FILE __). '/.. /yii/framework/YiiBase. php '; $ config = dirname (_ FILE __). '/protected/config/main. php '; // remove the following lines when in production modedefined ('yii _ debug') or define ('yii _ debug', true ); // specify how many levels of call stack shocould be shown in each log messagedefined ('yii _ TRACE_LEVEL ') or define ('yii _ TRACE_LEVEL', 3); require_on Ce ($ yii); // extension base class Yii extends YiiBase {/*** global extension method: factory function * @ param type $ alias class Library alias */static function instance ($ alias) {static $ _ class _ = array (); $ key = md5 ($ alias ); if (! Isset ($ _ class _ [$ key]) {$ _ class _ [$ key] = self: createComponent ($ alias );} return $ _ class _ [$ key] ;}} Yii: createWebApplication ($ config)-> run ();


This class is defined before the last Yii: createWebApplication () line to ensure that the Yii class can be used normally (do not put this class at the end of the file, it will cause errors .)

$ Obj = Yii: instance ($ alias); is used to instantiate a class anywhere in the project and is in Singleton mode.

Two important methods in YiiBase (import, autoload)
Then, let's take a look at the import method in YiiBase to see why these static variables are used:

/* Yii: import () * $ alias: name or path of the class to be imported * $ forceInclude false: import only non-include class files, true: import and include the class file */public static function import ($ alias, $ forceInclude = false) {// Yii puts all dependencies into the global $ _ imports array. the names cannot be repeated. // if the current dependency has been introduced, then directly return if (isset (self: $ _ imports [$ alias]) {return self ::$ _ imports [$ alias];} // the value of the second parameter of the class_exists and interface_exists methods is false, indicating not autoload if (class_exists ($ alias, false) | interface_exists ($ Alias, false) {return self: $ _ imports [$ alias] = $ alias ;} // if it is a class in the namespace format of php5.3 (for example, \ a \ B \ c. php) if ($ pos = strrpos ($ alias ,'\\'))! = False) {// $ namespace =. B $ namespace = str_replace ('\\','. ', ltrim (substr ($ alias, 0, $ pos),' \ '); // Judge. whether the PATH B exists or. B is only a key in alias. call this method to return the value of this key, for example, 'Email '=> realpath (_ DIR __. '/.. /vendor/cornernote/yii-email-module/email ') if ($ path = self: getPathOfAlias ($ namespace ))! = False) {$ classFile = $ path. DIRECTORY_SEPARATOR. substr ($ alias, $ pos + 1 ). '. php '; if ($ forceInclude) {if (is_file ($ classFile) {require ($ classFile);} else {throw new CException (Yii: t ('yii ', 'Alias "{Alias}" is invalid. make sure it points to an existing PHP file and the file is readable. ', array (' {alias} '=> $ alias);} self: $ _ imports [$ alias] = $ alias;} else {self :: $ classMap [$ alias] = $ ClassFile;} return $ alias;} else {// try to autoload the class with an autoloader if (class_exists ($ alias, true) {return self :: $ _ imports [$ alias] = $ alias;} else {throw new CException (Yii: t ('yii', 'Alias "{Alias}" is invalid. make sure it points to an existing directory or file. ', array (' {alias} '=> $ namespace) ;}} if ($ pos = strrpos ($ alias ,'. ') = false) // a simple class nam E {// try to autoload the class with an autoloader if $ forceInclude is true if ($ forceInclude & (Yii: autoload ($ alias, true) | class_exists ($ alias, true) {self ::$ _ imports [$ alias] = $ alias;} return $ alias;} $ className = (string) substr ($ alias, $ pos + 1); $ isClass = $ className! = '*'; If ($ isClass & (class_exists ($ className, false) | interface_exists ($ className, false) {return self :: $ _ imports [$ alias] = $ className;} if ($ path = self: getPathOfAlias ($ alias ))! = False) {if ($ isClass) {if ($ forceInclude) {if (is_file ($ path. '. php ') {require ($ path. '. php ');} else {throw new CException (Yii: t ('yii', 'Alias "{Alias}" is invalid. make sure it points to an existing PHP file and the file is readable. ', array (' {alias} '=> $ alias);} self: $ _ imports [$ alias] = $ className;} else {self :: $ classMap [$ className] = $ path. '. php ';} return $ className ;}// $ Alias is 'system. web. * 'to the end of *, add the path to 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); if (self :: $ enableIncludePath & set_include_path ('. '. PATH_SEPARATOR. implode (PATH_SEPARATOR, self ::$ _ includePaths) === false) {self ::$ enableIncludePath = false;} 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 )));}}

Yes, the above method finally put all the things to be loaded into $ _ imports, $ _ includePaths. This is the Yii import method. Okay, let's take a look at the autoload method:

public static function autoload($className, $classMapOnly = false){  // use include so that the error PHP file may appear  if (isset(self::$classMap[$className])) {         include(self::$classMap[$className]);  } elseif (isset(self::$_coreClasses[$className])) {      include(YII_PATH . self::$_coreClasses[$className]);  } elseif ($classMapOnly) {      return false;  } else {     // include class file relying on include_path        if (strpos($className, '\\') === false)     // class without namespace        {            if (self::$enableIncludePath === false) {                 foreach (self::$_includePaths as $path) {                          $classFile = $path . DIRECTORY_SEPARATOR . $className . '.php';                      if (is_file($classFile)) {                      include($classFile);                          if (YII_DEBUG && basename(realpath($classFile)) !== $className . '.php') {                              throw new CException(Yii::t('yii', 'Class name "{class}" does not match class file "{file}".', array(                '{class}' => $className,                '{file}' => $classFile,              )));                          }                          break;                     }               }         } else {              include($className . '.php');             }     } else // class name with namespace in PHP 5.3       {           $namespace = str_replace('\\', '.', ltrim($className, '\\'));         if (($path = self::getPathOfAlias($namespace)) !== false) {        include($path . '.php');           } else {              return false;           }       }    

Return class_exists ($ className, false) | interface_exists ($ className, false);} return true ;}
The classes or paths in the import items in the config file will be automatically imported during script startup. The Yii: import () statement can be added before the class definition of some classes in your application.

Articles you may be interested in:
  • Definition and binding of behavior in PHP Yii Framework
  • Detailed description of Behaviors in PHP Yii Framework
  • In-depth explanation of attributes in PHP Yii Framework)
  • Interpreting the request and response processing process in PHP Yii Framework
  • Tutorial on using database configuration and SQL operations in PHP Yii Framework
  • The example explains how to handle errors and exceptions in the PHP Yii Framework.
  • Parse related operations of cookie and session functions in PHP Yii Framework
  • Brief Analysis of basic knowledge about componentization mechanism of PHP Yii Framework
  • Describes the operating mechanism and routing function of the Yii Framework of PHP.
  • In-depth analysis of event mechanism in PHP Yii Framework
  • A comprehensive explanation of the log function in the PHP Yii Framework
  • How to remove the behavior bound to a component from the Yii Framework of PHP

After idea automatically creates an application through yiic. php, the initial code of the entry file is as follows: php // change the following paths...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.