首頁  >  文章  >  後端開發  >  php 解決專案中多個自動載入衝突問題

php 解決專案中多個自動載入衝突問題

藏色散人
藏色散人轉載
2020-01-10 17:36:502192瀏覽

在有的框架中的自動載入機制,在發現無法載入時, 直接報錯, 而沒有把控制權轉交給下一個自動載入方法., 如我要引入阿里雲日誌服務介面sdk,該sdk中自帶自動載入方法,如下:

<?php
/**
 * Copyright (C) Alibaba Cloud Computing
 * All rights reserved
 */
$version = &#39;0.6.0&#39;;
function Aliyun_Log_PHP_Client_Autoload($className) {
    $classPath = explode(&#39;_&#39;, $className);
    if ($classPath[0] == &#39;Aliyun&#39;) {
        if(count($classPath)>4)
            $classPath = array_slice($classPath, 0, 4);
        $filePath = dirname(__FILE__) . &#39;/&#39; . implode(&#39;/&#39;, $classPath) . &#39;.php&#39;;
        if (file_exists($filePath))
            require_once($filePath);
    }
}
spl_autoload_register(&#39;Aliyun_Log_PHP_Client_Autoload&#39;);

上面自動載入方法會與原始框架自己的載入方法衝突,解決方法如下:

<?php
function autoloadAdjust()
{
    // 取原有的加载方法
    $oldFunctions = spl_autoload_functions();
    // 逐个卸载
    if ($oldFunctions){
        foreach ($oldFunctions as $f) {
            spl_autoload_unregister($f);
        }
    }
    // 注册本框架的自动载入
    spl_autoload_register(
        # 就是aliyun sdk的加载方法
        function ($className) {
            $classPath = explode(&#39;_&#39;, $className);
            if ($classPath[0] == &#39;Aliyun&#39;) {
                    if(count($classPath)>4)
                    $classPath = array_slice($classPath, 0, 4);
                unset($classPath[0]);
                $filePath = dirname(__FILE__) . &#39;/&#39; . implode(&#39;/&#39;, $classPath) . &#39;.php&#39;;
                if (file_exists($filePath))
                    require_once($filePath);
            }
        }
    );
    // 如果引用本框架的其它框架已经定义了__autoload,要保持其使用
    if (function_exists(&#39;__autoload&#39;)) {
        spl_autoload_register(&#39;__autoload&#39;);
    }
    // 再将原来的自动加载函数放回去
    if ($oldFunctions){
        foreach ($oldFunctions as $f) {
            spl_autoload_register($f);
        }
    }
}
# 最后调用上面方法
autoloadAdjust();

注意在引入時,按照上面方法使用可能要改變程式碼中的檔案路徑

參考: 

近日,開發中,使用了ZF框架和一個自有框架進行配合.  

#先啟動了ZF, 之後,啟動自有框架,  這時發現自有框架的自動加載不生效.

雙方都使用了spl_autoload_register 對自動加載方法進行了註冊.

分析後發現, ZF的載入方法,在發現無法載入時, 直接報錯, 而沒有把控制權轉交給下一個自動載入方法.

如果先註冊自有框架的載入方法,就不會出問題.因為自有框架的自動載入方法找不到類別時,會返回False,這將控制權轉交給下一個載入方法

專案狀態導致註冊順序只能是ZF在前面.  查了手冊寫了下面的程式來調整註冊順序

#

以上是php 解決專案中多個自動載入衝突問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除