简体   繁体   English

基于 Laravel 5.4 环境的配置文件

[英]Laravel 5.4 environment based config files

I am trying to change the Laravel configuration variables based on environment, but I do not know how.我正在尝试根据环境更改 Laravel 配置变量,但我不知道如何更改。

Code to get config is获取配置的代码是

Config::get( 'contants.api_url' );

I am trying to have a separate results for the live environment and the development environment.我正在尝试为实时环境和开发环境提供单独的结果。

Real life scenario现实生活场景

I need to override some config files, so everybody who is using the development environment, has the same base configuration.我需要重写一些配置文件,以便使用开发环境的每个人都具有相同的基本配置。 I cannot use the.env file for this, because it is not shared between the team and everybody has their own version of it.我不能为此使用 .env 文件,因为它不是在团队之间共享的,每个人都有自己的版本。

What did I try:我尝试了什么:

I read here Laravel 5 configuration - environments and overriding that you can create subfolders within your /config folder, that match the environment, to override the default config files.我在这里阅读Laravel 5 配置 - 环境和覆盖,您可以在 /config 文件夹中创建与环境匹配的子文件夹,以覆盖默认配置文件。 Alas it did not work for me and the Laravel 5.4 documentation on the subject matter ( https://laravel.com/docs/5.4/configuration#retrieving-environment-configuration ) did not speak about this option, thus I believe it might have been deprecated.唉,它对我不起作用,关于主题的 Laravel 5.4 文档 ( https://laravel.com/docs/5.4/configuration#retrieving-environment-configuration ) 没有谈到这个选项,因此我相信它可能有已弃用。

One option could be to use a service provider.一种选择是使用服务提供商。 If you're only going to be overriding one or two values then you might as well just use your AppServiceProvider , otherwise I would suggest creating a new service (eg ConfigServiceProvider ).如果您只想覆盖一个或两个值,那么您也可以只使用AppServiceProvider ,否则我建议创建一个新服务(例如ConfigServiceProvider )。

In the boot() method of your service provider you could add something like:在您的服务提供商的boot()方法中,您可以添加如下内容:

if (app()->environment() === 'local') {
   config()->set('contants.api_url', 'http://example.com');
}

To change the configuration variables based on environment, this will do:要根据环境更改配置变量,可以这样做:

Example file: config/database.php示例文件: config/database.php

       'mysql' => [
            'driver' => mysql,
            'url' => env('DATABASE_URL'),
            'host'=> (env('APP_ENV') === 'local' ? env('DB_HOST_LOCAL') : env('DB_HOST_PRODUCTION')),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'default'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'options' => (env('APP_ENV') === 'local' ? [
                'some_option' =>  env('SOME_ENV')
            ] : []),
        ],

Tested and works on Laravel 5.8.经过测试并适用于 Laravel 5.8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM