当前位置:首页 > PHP教程 > php高级应用 > 列表

php 解决项目中多个自动加载冲突问题

发布:smiling 来源: PHP粉丝网  添加日期:2022-05-22 08:42:58 浏览: 评论:0 

在有的框架中的自动加载机制,在发现无法加载时, 直接报错, 而没有把控制权转交给下一个自动加载方法., 如我要引入阿里云日志服务接口sdk,该sdk中自带自动加载方法,如下:

  1. <?php 
  2.  
  3. /** 
  4.  
  5.  * Copyright (C) Alibaba Cloud Computing 
  6.  
  7.  * All rights reserved 
  8.  
  9.  */ 
  10.  
  11. $version = '0.6.0'; 
  12.  
  13. function Aliyun_Log_PHP_Client_Autoload($className) { 
  14.  
  15.     $classPath = explode('_', $className); 
  16.  
  17.     if ($classPath[0] == 'Aliyun') { 
  18.  
  19.         if(count($classPath)>4) 
  20.  
  21.             $classPath = array_slice($classPath, 0, 4); 
  22.  
  23.         $filePath = dirname(__FILE__) . '/' . implode('/', $classPath) . '.php'; 
  24.  
  25.         if (file_exists($filePath)) 
  26.  
  27.             require_once($filePath); 
  28.  
  29.     } 
  30.  
  31. } 
  32.  
  33. spl_autoload_register('Aliyun_Log_PHP_Client_Autoload'); 

上面自动加载方法会与原有框架自己的加载方法冲突,解决方法如下:

  1. <?php 
  2.  
  3. function autoloadAdjust() 
  4.  
  5. { 
  6.  
  7.     // 取原有的加载方法 
  8.  
  9.     $oldFunctions = spl_autoload_functions(); 
  10.  
  11.     // 逐个卸载 
  12.  
  13.     if ($oldFunctions){ 
  14.  
  15.         foreach ($oldFunctions as $f) { 
  16.  
  17.             spl_autoload_unregister($f); 
  18.  
  19.         } 
  20.  
  21.     } 
  22.  
  23.     // 注册本框架的自动载入 
  24.  
  25.     spl_autoload_register( 
  26.  
  27.         # 就是aliyun sdk的加载方法 
  28.  
  29.         function ($className) { 
  30.  
  31.             $classPath = explode('_', $className); 
  32.  
  33.             if ($classPath[0] == 'Aliyun') { 
  34.  
  35.                     if(count($classPath)>4) 
  36.  
  37.                     $classPath = array_slice($classPath, 0, 4); 
  38.  
  39.                 unset($classPath[0]); 
  40.  
  41.                 $filePath = dirname(__FILE__) . '/' . implode('/', $classPath) . '.php'; 
  42.  
  43.                 if (file_exists($filePath)) 
  44.  
  45.                     require_once($filePath); 
  46.  
  47.             } 
  48.  
  49.         } 
  50.  
  51.     ); 
  52.  
  53.     // 如果引用本框架的其它框架已经定义了__autoload,要保持其使用 
  54.  
  55.     if (function_exists('__autoload')) { 
  56.  
  57.         spl_autoload_register('__autoload'); 
  58.  
  59.     } 
  60.  
  61.     // 再将原来的自动加载函数放回去 
  62.  
  63.     if ($oldFunctions){ 
  64.  
  65.         foreach ($oldFunctions as $f) { 
  66.  
  67.             spl_autoload_register($f); 
  68.  
  69.         } 
  70.  
  71.     } 
  72.  
  73. } 

# 最后调用上面方法

autoloadAdjust();

注意在引入时,按照上面方法使用可能要改变代码中的文件路径

参考:

近日,开发中,使用了ZF框架和一个自有框架进行配合.

先启动了ZF, 之后,启动自有框架, 这时发现 自有框架的自动加载 不生效.

双方都使用了 spl_autoload_register 对自动加载方法进行了 注册.

分析后发现, ZF的加载方法,在发现无法加载时, 直接报错, 而没有把控制权转交给下一个自动加载方法.

如果先注册自有框架的加载方法,就不会出问题.因为自有框架的自动加载方法 找不到类时,会返回False,这将控制权转交给下一个加载方法

项目状态导致注册顺序只能是ZF在前面. 查了手册 写了下面的程序来调整注册顺序

Tags: php多个自动加载冲突

分享到: