Laravel 所有配置文件位於 config/ 目錄,每個文件返回關聯陣列。核心優勢:環境隔離、類型安全、緩存加速、運行時動態修改。
// 全局 helper 函數
$timezone = config('app.timezone'); // 獲取
$locale = config('app.locale', 'en'); // 帶默認值
// 運行時動態設置(僅影響當前請求)
config(['app.timezone' => 'America/Chicago']);
config(['database.connections.mysql.prefix' => 'new_']);
// 判斷配置是否存在
if (config('services.stripe.secret')) { ... }
基於 vlucas/phpdotenv 實現,.env 不提交版本控制,.env.example 作為模板提交。
# .env 示例 APP_NAME=Laravel APP_ENV=local APP_KEY=base64:xxx APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=https://localhost DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379
// env() 第二參數為默認值
'debug' => env('APP_DEBUG', false),
'url' => env('APP_URL', 'https://localhost'),
// 在配置文件中使用 env() 實現環境差異化
// config/database.php
'mysql' => [
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', 3306),
],
use Illuminate\Support\Facades\App;
$env = App::environment(); // 'local'
$isLocal = App::environment('local'); // true
$isProd = App::environment(['production', 'staging']); // 多環境匹配
// 或使用 helper
$env = app()->environment();
# 生成緩存文件 bootstrap/cache/config.php php artisan config:cache # 清除緩存 php artisan config:clear
原理:將所有 config/*.php 合併為單一陣列文件,框架啟動時直接 require,避免數十次文件 I/O 與解析開銷。
| 場景 | 操作 |
|---|---|
| 代碼部署上線 | 執行 php artisan config:cache |
| 修改 .env 後 | 執行 php artisan config:clear && php artisan config:cache |
| 本地開發 | 不要緩存,保持實時讀取 |
| CI/CD 流水線 | 構建階段執行緩存命令 |
# 開啟維護模式(返回 503) php artisan down # 可選參數 php artisan down --message="系統升級中" --retry=60 --allow=192.168.1.100 # 關閉維護模式 php artisan up
實現機制:down 創建 storage/framework/down 文件,中間件 CheckForMaintenanceMode 檢測到文件存在則拋出 MaintenanceModeException,渲染 resources/views/errors/503.blade.php。
系統維護中
🔧 系統維護中
{{ $message ?? '我們正在進行系統升級,請稍後再試。' }}
@if ($retry)
預計 {{ $retry }} 秒後恢復,頁面將自動重試...
@endif
// config/services.php - 第三方服務統一管理
return [
'stripe' => [
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
'aliyun' => [
'oss' => [
'key' => env('OSS_KEY'),
'secret' => env('OSS_SECRET'),
'bucket' => env('OSS_BUCKET'),
],
'sms' => [...],
],
];
// 中間件中根據租戶動態覆蓋配置
public function handle($request, \Closure $next) {
$tenant = $request->user()->tenant;
config([
'database.connections.tenant' => [
'database' => "tenant_{$tenant->id}",
'username' => $tenant->db_user,
'password' => $tenant->db_pass,
],
'filesystems.disks.tenant' => [
'root' => storage_path("app/tenants/{$tenant->id}"),
],
]);
return $next($request);
}
config:clear 重新緩存env('APP_DEBUG', false) 中字符串 'false' 會被解析為布爾 false,但 'true' 字符串也會被解析為 true