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

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

<?php

/**

 * Copyright (C) Alibaba Cloud Computing

 * All rights reserved

 */

$version = '0.6.0';

function Aliyun_Log_PHP_Client_Autoload($className) {

    $classPath = explode('_', $className);

    if ($classPath[0] == 'Aliyun') {

        if(count($classPath)>4)

            $classPath = array_slice($classPath, 0, 4);

        $filePath = dirname(__FILE__) . '/' . implode('/', $classPath) . '.php';

        if (file_exists($filePath))

            require_once($filePath);

    }

}

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 }
74 
75 # 最后调用上面方法
76 
77 autoloadAdjust();

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

猜你喜欢

转载自www.cnblogs.com/mo3408/p/12184579.html