LoginSignup
5
7

More than 5 years have passed since last update.

Laravel の Config はキャッシュに気をつけるべき

Posted at

Laravel の Config はキャッシュされるので、かなりはまった。

特にCI周りでは注意が必要。

優先順位

bootstrap/cache/config.php > phpunit.xml > .env

なので、ユニットテスト時に DB_HOST を変える、などしたくてもキャッシュされている場合うまくいかない。

なので、こういうコードで解決した。
他にいいやり方があれば教えてほしい。

tests/TestCase.php
<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase {

    // ...

    public function createApplication()
    {
        // testing 環境でもlocal 環境を見に行ってしまうため
        // キャッシュを読み込まないようにしている
        // TODO: もっとエレガントな方法を模索する
        if (file_exists(__DIR__.'/../bootstrap/cache/config.php'))
            unlink(__DIR__.'/../bootstrap/cache/config.php');

        $app = require __DIR__.'/../bootstrap/app.php';

        // ...

        return $app;
    }
}

$this->artisan('config:cache')$app が未定義の状態ではできない。
かつ、恐らく $app が生成されると、その時点で環境変数を読むため、実質不可能である(要調査)。

環境変数

php artisan config:cache する時、

環境変数 > .env

となるので、

/etc/profile
export APP_ENV=testing
.env
APP_ENV=local

の状態で php artisan config:cache すると

APP_ENV=testing となる。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7