2014-10-03 33 views
6

作曲自動加載多個文件,我在我的最新項目中使用的作曲家和我的映射功能,這樣在文件夾

"require": { 
    ... 
}, 
"require-dev": { 
    ... 
}, 
"autoload": { 
    "psr-4": { 
     ... 
    }, 
    "files": [ 
     "src/function/test-function.php" 
    ] 
} 

我想會有很多的文件夾中的功能,例如:實時功能-1.php,real-function-2.php等等,那麼作曲家可以調用文件夾中的所有文件嗎?我懶得用

"files": [ 
    "src/function/real-function-1.php", 
    "src/function/real-function-2.php", 
    .., 
    "src/function/real-function-100.php", 
] 

有沒有偷懶跟我一樣......

+1

這就是'autoload'函數的工作。它會自動加載「主文件」,這通常會包含一系列require語句。 [這是一個例子](https://github.com/WhitePayments/white-php/blob/master/White.php) – FloatingRock 2014-10-03 06:12:33

回答

11

如果您不能命名空間的功能(因爲它會破壞一串代碼,或者因爲你不能使用PSR -4),並且你不想製作靜態類來保存你的函數(然後可以自動加載),你可以製作你自己的全局包含文件,然後告訴作曲者將它包含進去。

composer.json

{ 
    "autoload": { 
     "files": [ 
      "src/function/include.php" 
     ] 
    } 
} 

include.php

$files = glob(__DIR__ . '/real-function-*.php'); 
if ($files === false) { 
    throw new RuntimeException("Failed to glob for function files"); 
} 
foreach ($files as $file) { 
    require_once $file; 
} 
unset($file); 
unset($files); 

這是不理想的,因爲它會加載爲每個請求每個文件,而不管是否將功能在它被使用,但它會工作。