목차
PHP的Yii框架中YiiBase入口类的扩展写法示例,yiiyiibase
您可能感兴趣的文章:
백엔드 개발 PHP 튜토리얼 PHP的Yii框架中YiiBase入口类的扩展写法示例,yiiyiibase_PHP教程

PHP的Yii框架中YiiBase入口类的扩展写法示例,yiiyiibase_PHP教程

Jul 12, 2016 am 08:56 AM
ecshop php yii

PHP的Yii框架中YiiBase入口类的扩展写法示例,yiiyiibase

通过yiic.php自动创建一个应用后,入口文件初始代码如下:

<&#63;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 mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($yii);
Yii::createWebApplication($config)->run();

로그인 후 복사


其中第三行引入了一个yii.php的文件,这个可以在yii核心目录里的framework/下找到,这个文件中定义了一个Yii类,并且继承了YiiBase类。

代码如下

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 <qiang.xue@gmail.com>
 * @package system
 * @since 1.0
 */
class Yii extends YiiBase
{
}
로그인 후 복사

Yii::createWebApplication
로그인 후 복사

这个方法实际上是在YiiBase父类中定义的,所以,Yii为我们预留了扩展的可能。我们只需要在yii.php中添加我们想要扩展的方法即可,在项目中直接使用 Yii::方法名() 调用。
为了将项目代码和核心目录完全分离,我个人觉得在项目目录下使用另外一个yii.php来替代从核心目录中包含yii.php更加好。

这里我用了更加极端的方法,我直接将yii这个类定义在了入口文件,并扩展了一个全局工厂函数 instance()方法,请看代码:

<&#63;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 mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($yii);
//扩展基类
class Yii extends YiiBase{
  /**
   * 全局扩展方法:工厂函数
   * @param type $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();

로그인 후 복사


这个类是在最后一行Yii::createWebApplication()之前定义的,以保证Yii类能正常使用(不要把这个类放在文件末尾,会出错。)

在项目中任何地方,使用$obj = Yii::instance($alias);去实例化一个类,并且是单例模式。

YiiBase中的两个比较重要的方法 (import,autoload)
然后看看YiiBase中的import方法就知道这些静态变量是干嘛用的了:

 /* Yii::import()
* $alias: 要导入的类名或路径
* $forceInclude false:只导入不include类文件,true则导入并include类文件
*/
 public static function import($alias, $forceInclude = false){  
 //Yii把所有的依赖放入到这个全局的$_imports数组中,名字不能重复
 //如果当前依赖已经被引入过了,那么直接返回
 if (isset(self::$_imports[$alias])) {    
    return self::$_imports[$alias];  
  }  
 //class_exists和interface_exists方法的第二个参数的值为false表示不autoload 
 if (class_exists($alias, false) || interface_exists($alias, false)) {    
   return self::$_imports[$alias] = $alias;  
 }  
 //如果传进来的是一个php5.3版本的命名空间格式的类(例如:\a\b\c.php)
 if (($pos = strrpos($alias, '\\')) !== false) {    
  //$namespace = a.b
  $namespace = str_replace('\\', '.', ltrim(substr($alias, 0, $pos), '\\')); 
  //判断a.b这个路径是否存在,或者a.b只是alias里面的一个键,调用该方法返回这个键对应的值,比如'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 name 
 {    
  // 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是'system.web.*'这样的已*结尾的路径,将路径加到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);      
    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)));  
    }
 }

로그인 후 복사

是的,上面这个方法最后就把要加载的东西都放到$_imports,$_includePaths中去了。这就是Yii的import方法,好的,接下来我们看看autoload方法:

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;}
config文件中的 import 项里的类或路径在脚本启动中会被自动导入。用户应用里个别类需要引入的类可以在类定义前加入 Yii::import() 语句。

您可能感兴趣的文章:

  • PHP的Yii框架中行为的定义与绑定方法讲解
  • 详解在PHP的Yii框架中使用行为Behaviors的方法
  • 深入讲解PHP的Yii框架中的属性(Property)
  • 解读PHP的Yii框架中请求与响应的处理流程
  • PHP的Yii框架中使用数据库的配置和SQL操作实例教程
  • 实例讲解如何在PHP的Yii框架中进行错误和异常处理
  • 解析PHP的Yii框架中cookie和session功能的相关操作
  • 简要剖析PHP的Yii框架的组件化机制的基本知识
  • 详解PHP的Yii框架的运行机制及其路由功能
  • 深入解析PHP的Yii框架中的event事件机制
  • 全面解读PHP的Yii框架中的日志功能
  • PHP的Yii框架中移除组件所绑定的行为的方法

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1111322.htmlTechArticlePHP的Yii框架中YiiBase入口类的扩展写法示例,yiiyiibase 通过yiic.php自动创建一个应用后,入口文件初始代码如下: php// change the following paths...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP 날짜 및 시간 CakePHP 날짜 및 시간 Sep 10, 2024 pm 05:27 PM

cakephp4에서 날짜와 시간을 다루기 위해 사용 가능한 FrozenTime 클래스를 활용하겠습니다.

CakePHP 토론 CakePHP 토론 Sep 10, 2024 pm 05:28 PM

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

CakePHP 파일 업로드 CakePHP 파일 업로드 Sep 10, 2024 pm 05:27 PM

파일 업로드 작업을 위해 양식 도우미를 사용할 것입니다. 다음은 파일 업로드의 예입니다.

CakePHP 유효성 검사기 만들기 CakePHP 유효성 검사기 만들기 Sep 10, 2024 pm 05:26 PM

컨트롤러에 다음 두 줄을 추가하면 유효성 검사기를 만들 수 있습니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

CakePHP 빠른 가이드 CakePHP 빠른 가이드 Sep 10, 2024 pm 05:27 PM

CakePHP는 오픈 소스 MVC 프레임워크입니다. 이를 통해 애플리케이션 개발, 배포 및 유지 관리가 훨씬 쉬워집니다. CakePHP에는 가장 일반적인 작업의 과부하를 줄이기 위한 여러 라이브러리가 있습니다.

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

See all articles