Laravel 專案常需整合非 Composer 套件、專案私有類庫或舊版程式碼。本文詳細說明三種整合方案:classmap 直接對應、files 載入助手函式、PSR-4 規範命名空間自動載入,含實戰配置與最佳實踐。
app/Libraries/Class/Message.php
<?php
class Message {
public static function display() {
return 'Hello from custom library!';
}
}
composer.json autoload.classmap
"autoload": {
"classmap": [
"app/Commands",
"app/Controllers",
"app/Models",
"app/Libraries/Class" // 新增此行
]
}
composer dump-autoload
Message::display(); // 即可呼叫
app/Libraries/Functions/helpers.php
<?php
function v($data) {
var_dump($data);
}
function config_path($path = '') {
return config_path($path);
}
composer.json autoload.files
"autoload": {
"classmap": [...],
"files": [
"app/Libraries/Functions/helpers.php"
]
}
composer dump-autoload 後全域可用
v($user); // 任何地方直接呼叫
// bootstrap/app.php 或 AppServiceProvider::register()
require_once app_path('Libraries/Functions/helpers.php');
// 或在中介層載入 (按需載入)
\App::before(function ($request) {
require_once app_path('Libraries/Functions/helpers.php');
});
app/Libraries/
└── MyApp/
├── Search/
│ ├── Search.php // namespace MyApp\Search;
│ ├── SearchFacade.php
│ └── SearchServiceProvider.php
└── Payment/
├── Gateway.php
└── Contracts/
└── GatewayInterface.php
"autoload": {
"classmap": [...],
"psr-4": {
"MyApp\\": "app/Libraries" // 命名空間前綴 -> 實體目錄
}
}
use MyApp\Search\Search; use MyApp\Payment\Gateway; $search = new Search(); $gateway = new Gateway();
// MyApp/Search/SearchServiceProvider.php
namespace MyApp\Search;
use Illuminate\Support\ServiceProvider;
class SearchServiceProvider extends ServiceProvider {
public function register() {
$this->app->singleton('search', function ($app) {
return new Search($app['config']->get('search'));
});
}
public function boot() {
// 發布設定檔、遷移等
}
}
// 設定檔 config/app.php 新增提供者
'providers' => [
// ...
MyApp\Search\SearchServiceProvider::class,
],
// 可選:註冊 Facade
'aliases' => [
'Search' => MyApp\Search\SearchFacade::class,
];
| 需求 | 推薦方案 | 理由 |
|---|---|---|
| 單一類別、無命名空間、快速整合 | ClassMap | 零配置、即插即用 |
| 全域函式、助手工具 | Files | 自動全域可用、無需 import |
| 多類別、有命名空間、團隊專案 | PSR-4 | 標準化、IDE 友善、易維護擴充 |
| 需 Laravel 服務容器、Facade、設定檔 | PSR-4 + ServiceProvider | 深度整合框架生態 |
app/Libraries 或 app/Packages