[英]Spl_autoload_register does not working with external libraries
我有一個非常簡單的spl_autoload_register函數:
spl_autoload_register(function($file) {
require_once str_replace('\\', '/', $file) . '.php';
});
在我的課程中,一切正常。 我在每個類的開頭使用名稱空間,並像$class = new \\system\\controller\\Front();
一樣使用它$class = new \\system\\controller\\Front();
。
但是現在,我想使用此外部庫/類https://github.com/leafo/lessphp/blob/master/lessc.inc.php 。 我還在開頭的namespace system\\lib\\less;
添加了名稱namespace system\\lib\\less;
並嘗試使用方法compileFile()
,但出現錯誤Warning: require_once(lessc.php): failed to open stream: No such file or directory in
。
我發現,該類lessc()
首次初始化成功,但是錯誤出現在第n行no. 2442
no. 2442
- $commentSingle = lessc::preg_quote(self::$commentSingle);
使用lessc::
地方。
我的spl_autoload_register
函數無法處理該問題,因為沒有在類名稱之前添加名稱空間,並嘗試僅加載lessc.php
文件。
我的問題是,如何全局地修復我想添加到項目中的所有其他類/庫,而不編輯它們(通過添加名稱空間)。 有什么解決方案嗎?
我發現的唯一解決方案是將spl_autoload_register
函數更改為類似的方法,這似乎可行,但是我不知道這是否是正確且最佳的解決方案,並且我不知道此方法是否適用於所有外部庫喜歡使用。
spl_autoload_register(function($file) {
// external libraries
if ($file === 'lessc') $file = 'system/lib/less/lessc';
require_once str_replace('\\', '/', $file) . '.php';
});
我認為我可能傾向於創建一個json文件,該文件將創建位置處理記錄,類似於作曲家的工作方式。 您可以根據特定庫的命名來使其處理不同的場景,但是命名范圍可能不會很大。 如今,知名的庫非常適合在命名和名稱空間方面保持最佳實踐:
/vendor.pref
[
{
"name": "lessc",
"include": "/system/lib/less/lessc.php"
},
{
"name": "other",
"root": "/system/lib/other",
"type": "psr0"
}
]
自動翻頁器
spl_autoload_register(function($class) {
# If there is a standard namespace
$file = str_replace('//','/',__DIR__.'/'.str_replace('\\', '/', $class)) . '.php';
# Check is file and include
if(is_file($file)) {
include_once($file);
return false;
}
# See if there is a vendor file and iterate through it to see if something is set up.
$json = __DIR__.'/vendor.json';
if(!is_file($json)) {
return false;
}
# Get the contents and convert to array
$vendors = json_decode(file_get_contents($json), true);
# Loop through it
foreach($vendors as $vendor) {
# See if the name in the json matches anything in the class
if(stripos($class, $vendor['name']) !== false) {
# If there is an include file, try and include it
if(isset($vendor['include']) && is_file($inc = __DIR__.$vendor['include'])) {
include_once($inc);
return false;
}
# You can do other autoload options as well that would be
# indicated in your json file. You can use other psr types
# so that you can try replacing _ (instead of \) with /
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.