Laravel 部署优化实战:config:cache 之后 env() 变 null 的根因与正确配置链
本地好好的,一上线配置全空
支付回调在预发环境正常,发到生产却一直报密钥为空。查日志发现第三方接口返回鉴权失败,而 .env 里那行 KEY 写得清清楚楚,php artisan tinker 里读 env 也能拿到。差别只在部署脚本多跑了一句 php artisan optimize:它把配置缓存了起来。这类问题特别容易误判成环境变量没注入、容器没挂载 .env,于是运维反复重启、重建镜像,浪费半天也定位不到。真正的原因是 Laravel 在配置缓存生效后会跳过 .env 加载,业务代码里直接调用 env() 拿到的就是 null。
<?php
namespace App\Http\Controllers;
use App\Models\Order;
class PayController extends Controller
{
public function charge(Order $order)
{
// 生产环境 config:cache 之后这里返回 null
$key = env('BILLING_API_KEY');
$client = new BillingClient($key);
return $client->charge($order->amount);
}
}
根因:配置缓存把 .env 从请求生命周期里摘掉了
正常启动时,Laravel 逐个加载 config 目录下的 PHP 文件,这些文件里的 env() 由 Dotenv 提供值。执行 php artisan config:cache 后,框架把所有 config 文件合并成单个 bootstrap/cache/config.php,之后的每次请求直接 require 这一个文件,不再解析 .env、也不再逐个读配置文件。既然 .env 根本没被加载,散落在控制器、路由、任务、Blade 里的 env() 自然只能返回 null。这不是 bug,而是官方明确写进文档的约束:只有 config 目录里的文件允许调用 env()。
# 生成 cached 配置:bootstrap/cache/config.php
php artisan config:cache
# 删除缓存,回到逐文件解析(排查「改了 .env 不生效」时常用)
php artisan config:clear
# Laravel 10+ 查看生效值,比 dd(env()) 可靠
php artisan config:show services
唯一正确的取值链路:env 进 config,业务只读 config
把外部变量收进一个配置文件,业务代码一律用 config() 读取。这样一来值在缓存生成时就被固化进 config.php,无论是否开启缓存结果都一致;同时配置有了明确的命名空间,测试里用 Config::set 覆盖也方便。新增变量时记得重新跑一次 config:cache,否则线上仍是旧值。给外部服务单独建 config/billing.php 比塞进 services.php 更好找,尤其是密钥多、还要区分沙箱与生产的时候。
<?php
// config/billing.php
return [
'key' => env('BILLING_API_KEY'),
'secret' => env('BILLING_API_SECRET'),
'sandbox' => (bool) env('BILLING_SANDBOX', false),
'timeout' => (int) env('BILLING_TIMEOUT', 10),
'base_uri' => env('BILLING_BASE_URI', 'https://api.example.com'),
];
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Support\Facades\Config;
class PayController extends Controller
{
public function charge(Order $order)
{
$key = Config::get('billing.key');
if (empty($key)) {
throw new \RuntimeException('缺少 billing.key,检查 .env 与配置缓存');
}
$client = new BillingClient($key, [
'timeout' => Config::get('billing.timeout'),
'sandbox' => Config::get('billing.sandbox'),
]);
return $client->charge($order->amount);
}
}
把配置收成类型化对象,顺手解决可测试性
散落的 config() 调用会让单元测试依赖全局状态。更稳的做法是在服务提供者里把配置解析成一个只读值对象并绑定为单例,控制器与任务只依赖这个对象。类型固定之后,少一个字段、类型写错都能在容器解析阶段暴露,测试里直接 new 一个对象注入即可,不用再 Config::set 一堆键。
<?php
namespace App\Support;
final class BillingConfig
{
public function __construct(
public readonly string $key,
public readonly string $secret,
public readonly bool $sandbox,
public readonly int $timeout,
public readonly string $baseUri,
) {}
public static function fromArray(array $c): self
{
if (empty($c['key']) || empty($c['secret'])) {
throw new \InvalidArgumentException('billing 凭据未配置');
}
return new self(
(string) $c['key'],
(string) $c['secret'],
(bool) ($c['sandbox'] ?? false),
(int) ($c['timeout'] ?? 10),
(string) ($c['base_uri'] ?? 'https://api.example.com'),
);
}
}
<?php
namespace App\Providers;
use App\Support\BillingConfig;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(BillingConfig::class, function ($app) {
return BillingConfig::fromArray($app['config']->get('billing'));
});
}
}
<?php
namespace Tests\Unit;
use App\Support\BillingConfig;
use PHPUnit\Framework\TestCase;
class BillingConfigTest extends TestCase
{
public function test_missing_key_is_rejected(): void
{
$this->expectException(\InvalidArgumentException::class);
BillingConfig::fromArray(['key' => '', 'secret' => '']);
}
public function test_defaults_are_applied(): void
{
$c = BillingConfig::fromArray(['key' => 'k', 'secret' => 's']);
$this->assertSame(10, $c->timeout);
$this->assertFalse($c->sandbox);
}
}
部署脚本里的顺序与几个隐形限制
缓存是「当前代码状态」的快照,必须在新代码就位、迁移完成之后最后重建,且每次发布都要重建。Laravel 11 起 php artisan optimize 一次性生成 config、event、route、view 四类缓存,optimize:clear 一次清掉,比逐条记命令省心。route:cache 有个硬限制:路由里不能出现闭包,因为闭包无法序列化,遇到就把闭包挪到控制器。还有两个常被忽略的点:每台机器或容器的 bootstrap/cache 是各自独立的,只在跳板机上跑一次不算数;PHP-FPM、队列 worker、Horizon、Octane 这些常驻进程会把配置留在内存里,发布后需要 reload 或重启,否则新配置不生效。
#!/usr/bin/env bash
set -euo pipefail
cd /var/www/app
# 1. 先拉新代码、装依赖
git pull --ff-only
composer install --no-dev --optimize-autoloader --no-interaction
# 2. 结构变更
php artisan migrate --force
# 3. 清掉上一版缓存,再按新代码重建(顺序不能反)
php artisan optimize:clear
php artisan optimize
# 4. 常驻进程必须重载,否则仍在用内存里的旧配置
php artisan queue:restart
sudo systemctl reload php8.3-fpm
# 5. 发布后抽查生效值
php artisan config:show billing
<?php
// routes/web.php —— 闭包路由会让 route:cache 失败
Route::get('/health', function () {
return response()->json(['ok' => true]);
});
// 改成控制器后即可被序列化缓存
Route::get('/health', [HealthController::class, 'index']);
本地开发与工程化注意点
本地不要开配置缓存,否则改 .env 会毫无反应,容易陷入「我明明改了」的排查循环;误开过一次就跑 php artisan optimize:clear。CI 里加一条静态检查,禁止 config 目录之外出现 env( 调用,比靠 code review 兜底可靠得多;用 grep 扫 app、routes、resources 三个目录即可,注意排除注释里的说明文字。
#!/usr/bin/env bash
# ci/check-env-usage.sh —— 阻止业务代码直接读 env()
set -euo pipefail
hits=$(grep -RIn --include='*.php' 'env(' app routes resources 2>/dev/null || true)
if [ -n "$hits" ]; then
echo "config 目录之外禁止调用 env(),请改用 config():"
echo "$hits"
exit 1
fi
echo "env() 使用检查通过"
- 只有 config 目录下的文件可以调用 env(),业务代码一律用 config();这是 config:cache 生效后的硬性约束。
- config:cache 生成 bootstrap/cache/config.php,config:clear 删除它;改了 .env 或配置文件后必须重新生成。
- Laravel 11 起用 php artisan optimize 一次生成 config、event、route、view 缓存,optimize:clear 一次清理。
- route:cache 不支持闭包路由,把逻辑挪进控制器;用 config:show 抽查线上实际生效值,别再用 dd(env())。
- 部署顺序是「新代码就位到迁移完成到清旧缓存到重建缓存」,且每台机器与容器都要各自执行,缓存不共享。
- PHP-FPM、队列 worker、Horizon、Octane 常驻进程持有内存中的旧配置,发布后需要 reload 或 queue:restart。
- 本地开发不要开配置缓存;CI 加静态检查禁止 config 目录外的 env( 调用,把问题拦在合并前。
把这条链路理顺之后,配置读取只有一种写法,环境变量只在配置文件里出现一次,本地与生产的行为差异就此消失。部署脚本里那几行 optimize 也不再是碰运气的加速项:它明确要求代码、缓存与常驻进程三者同步刷新,按这个顺序做,密钥为空这类问题就不会再拖到线上才发现。
未来之星
文章作者
本地好好的,一上线配置全空 支付回调在预发环境正常,发到生产却一直报密钥为空。查日志发现第三方接口返回鉴权失败,而 ....
- 分类
- 技术
- 发布时间
- 2026-11-17
- 字数
- 约 6277 字
- 阅读
- 11 次
