Examples of extensions to the Yiibase portal class in the PHP yii framework, yiiyiibase_php tutorial

Source: Internet
Author: User
Tags autoload autoloader

An example of an extension of the Yiibase entry class in the Yii framework of PHP, Yiiyiibase


After an app is automatically created by yiic.php, the entry file initial code 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 is shown in each log messagedefined (' Yii_trace_level ') or Def INE (' Yii_trace_level ', 3); require_once ($YII); Yii::createwebapplication ($config)->run ();


The third line introduces a yii.php file, which can be found under framework/in the Yii core directory, which 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{}
 
  

and

Yii::createwebapplication

This method is actually defined in the Yiibase parent class, so Yii has reserved the possibility for us to extend it. We just need to add the method we want to extend in yii.php, using the Yii:: Method Name () call directly in the project.
In order to completely separate the project code from the core directory, I personally feel that it is better to use another yii.php in the project directory instead of including yii.php from the core directory.

Here I used the more extreme method, I directly defined the Yii class in the portal file, and extended a global factory function instance () method, see 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 should is shown in each log messagedefined (' Yii_trace_level ') or Def INE (' Yii_trace_level ', 3); require_once ($yii);//Extended 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 line yii::createwebapplication () to ensure that the Yii class is working properly (do not put this class at the end of the file, it will go wrong.) )

Anywhere in the project, use $obj = Yii::instance ($alias), instantiate a class, and singleton mode.

Two more important methods in

yiibase (import,autoload)
then look at the import method in Yiibase to know what these static variables are for:

 /* Yii::import () * $alias: Class name or path to import * $forceInclude false: Import not include class file only, true import and include class file */public static function Import ($alias, $forceInclude = False) {//yii All dependencies into this global $_imports array, the name cannot be duplicated//if the current dependency has been introduced, then return directly 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 to indicate autoload if (Class_exists ($alias, false) | | interface_exists ($   Alias, False)) {return self::$_imports[$alias] = $alias; }//If it is passed in a php5.3 version of the namespace format of the class (for example: \a\b\c.php) if (($pos = Strrpos ($alias, ' \ \ '))!== false) {//$namespace = A.B $   namespace = str_replace (' \ \ ', '. ', LTrim (substr ($alias, 0, $pos), ' \ \ ')); Determine whether a.b this path exists, or A.B is just a key inside the alias, call the method to return the value corresponding to this key, such as ' email ' and 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 a 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 S        elf::$_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 name {//try to autoload the class wit H an autoloader if $forceInclude are 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::$_im   ports[$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 a 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 the ' system.web.* ' path that has been terminated, adding the path to include_path, else/a directory {if (Self::$_includepath             s = = = 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, this method finally puts everything you want to load into the $_imports,$_includepaths. This is the import method of Yii, OK, next we look at the AutoLoad method:

public static function AutoLoad ($className, $classMapOnly = False) {//use include ' so ' 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 wit  Hout 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 ', ' class name ' {class} 'does not match class file "{file}". ', Array (' {class} ' = = $className, ' {file} ' = = $cla                          Ssfile,)));                     } break; }}} else {include ($className.             '. php '); }} else//class name with namespace in PHP 5.3 {$namespace = str_replace (' \ \ ', '. ', LTrim ($classNam         e, ' \ \ ')); if ($path = Self::getpathofalias ($namespace))!== false) {include ($path.           '. php ');           } else {return false;     }       }

Return Class_exists ($className, false) | | Interface_exists ($className, false); } return true;
The class or path in the import entry in the config file is automatically imported in the script startup. Classes that need to be introduced by individual classes in the user application can include the Yii::import () statement before the class definition.

Articles you may be interested in:

    • The definition and binding methods of behavior in the YII framework of PHP
    • A detailed approach to using behavioral behaviors in the PHP yii framework
    • In-depth explanation of properties in the Yii framework of PHP
    • Interpreting the process of request and response in the YII framework of PHP
    • PHP's YII framework uses database configuration and SQL Operations example tutorials
    • Examples of how to do error and exception handling in the PHP yii framework
    • Parsing of PHP in the YII framework of the cookie and session function related operations
    • A brief analysis of the basic knowledge of the modular mechanism of the YII framework of PHP
    • The operation mechanism and routing function of the YII framework of PHP
    • In-depth parsing of event events mechanism in the YII framework of PHP
    • Full interpretation of the log function in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework

http://www.bkjia.com/PHPjc/1111322.html www.bkjia.com true http://www.bkjia.com/PHPjc/1111322.html techarticle PHP's Yii framework in the Yiibase entry class extension example, Yiiyiibase through yiic.php automatically created an app, the entry file initial code is as follows: php//change the following paths ...

  • 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.