Laravel允許您指定替代環境文件,繞過標準
文件。這對於測試特別有用,其中專用.env
文件可以隔離測試配置。雖然並非總是必要的,但此功能通過利用.env.testing
>環境變量來提供靈活性。 APP_ENV
>
>文件,例如:.env.demo
>
# Create .env.demo cp .env .env.demo echo "\nEXAMPLE_SETTING=demo" >> .env.demo # Use the `demo` env php artisan tinker --env=demo # Or set APP_ENV APP_ENV=demo php artisan tinker
.env.demo
。
.env
>使用而不是
.env.demo
.env
.env.testing
>對於Phpunit測試,默認值是使用.env
。 但是,這可能導致與本地開發設置(尤其是有關數據庫)的衝突。 phpunit.xml
提供數據庫配置,使用.env.testing
提供了一種更清潔的方法。
設置phpunit.xml
APP_ENV
進行“測試”,促使Laravel在功能測試期間加載.env.testing
:
<env name="APP_ENV" value="testing"></env>
創建.env.testing
並添加特定於測試的設置:
cp .env .env.testing echo "\nEXAMPLE_SETTING=testing" >> .env.testing
驗證.env.testing
已加載,將其添加到tests/Feature
>中的測試中:
/** * A basic test example. */ public function test_the_application_returns_a_successful_response(): void { logger('Which environment file is Laravel using?', [ 'file' => $this->app->environmentFile() ]); $response = $this->get('/'); $response->assertStatus(200); }
運行phpunit
應該登錄:
<code>[2024-05-24 00:22:42] testing.DEBUG: Which environment file is Laravel using? {"file":".env.testing"}</code>
是否要版本控制.env.testing
(或使用示例.env.testing.example
)是團隊的決定。 對於CI,建議使用測試數據庫等設置系統級環境變量。 有關更詳細的環境配置,請參閱官方的Laravel文檔。 要更深入地了解框架的實現,請檢查Laravel源代碼中的setEnvironmentFilePath
和checkForSpecificEnvironmentFile
方法。
以上是用其他環境文件配置Laravel的詳細內容。更多資訊請關注PHP中文網其他相關文章!