執行時修改 config/cache.php 的 default 值,適用於多環境、多租戶、測試切換:
<?php
// 切換至 Redis
Config::set('cache.default', 'redis');
var_dump(Config::get('cache.default')); // "redis"
// 切換至 Memcached
Config::set('cache.default', 'memcached');
var_dump(Config::get('cache.default')); // "memcached"
// 驗證實際存取
Cache::put('test_key', 'value', 60);
echo Cache::get('test_key'); // value
// 注意:僅影響當前請求生命週期,不會持久化到配置檔
?>
Laravel 服務容器綁定的 Facade 可用兩種方式存取:
<?php
// 完整命名空間
\Illuminate\Support\Facades\Cache::put('key', 'value');
// 根命名空間別名 (config/app.php aliases 設定)
Cache::put('key', 'value'); // 等同以上
// 原理:config/app.php
'aliases' => [
'Cache' => \Illuminate\Support\Facades\Cache::class,
// ...
]
// 服務容器綁定鍵名通常為小寫單數:cache, session, auth, db, log...
?>
常見錯誤:Unable to create directory storage/framework/cache/data 或 The stream or file could not be opened
# 1. 確認 Web 伺服器執行用戶 (nginx.conf / php-fpm.conf)
# 通常為 www-data (Debian/Ubuntu) 或 nginx (CentOS/RHEL) 或 www
# 2. 遞歸修改擁有者
chown -R www:www storage bootstrap/cache
# 3. 設定目錄權限 (775) 與檔案權限 (664)
find storage -type d -exec chmod 775 {} \;
find storage -type f -exec chmod 664 {} \;
find bootstrap/cache -type d -exec chmod 775 {} \;
find bootstrap/cache -type f -exec chmod 664 {} \;
# 4. 若使用 ACL (更精細控制)
setfacl -R -m u:www:rwx storage bootstrap/cache
setfacl -R -d -m u:www:rwx storage bootstrap/cache
# 5. 清除配置/路由/視圖快取
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear
# 6. 重新優化 (生產環境)
php artisan config:cache
php artisan route:cache
php artisan view:cache
| 症狀 | 可能原因 | 檢查指令 |
|---|---|---|
| 無法寫入 storage/logs | 目錄擁有者非 Web 用戶 | ls -la storage/ |
| 快取讀寫失敗 | storage/framework/cache 權限不足 | ls -la storage/framework/ |
| 上傳檔案失敗 | storage/app/public 不可寫 | ls -la storage/app/ |
| Session 檔案錯誤 | storage/framework/sessions 權限 | ls -la storage/framework/sessions/ |
| 視圖編譯失敗 | storage/framework/views 權限 | ls -la storage/framework/views/ |
<?php
// 程式化清除
Artisan::call('cache:clear');
Artisan::call('config:clear');
Artisan::call('route:clear');
Artisan::call('view:clear');
Artisan::call('optimize:clear'); // Laravel 9+ 包含以上所有
?>
<?php
// 運行時切換預設連線
Config::set('database.default', 'pgsql');
// 或指定模型連線
$users = User::on('pgsql')->get();
// 查詢建構器
DB::connection('mysql')->table('users')->get();
?>
<?php
// 僅影響當前進程
putenv('APP_ENV=testing');
$_ENV['APP_ENV'] = 'testing';
$_SERVER['APP_ENV'] = 'testing';
// 注意:config() 已快取不會重新讀取 .env
?>
Config::set() 不會寫入 .env 或 config/*.php,僅記憶體生效config:cache 後 env() 返回 null,務必在配置檔用 env('KEY', 'default')