覆盖特定环境的单个配置值

时间:2016-06-22 14:10:57

标签: php laravel laravel-4

在我的默认app.php文件中,我有如下定义的服务提供者和别名:

提供商:

'providers' => array(
    'Illuminate\Session\CommandsServiceProvider',
    'Illuminate\Html\HtmlServiceProvider',
    'SomeNamespace\Mail\MailServiceProvider',
    ...
),

别名:

'aliases' => array(
    'App'             => 'Illuminate\Support\Facades\App',
    'Artisan'         => 'Illuminate\Support\Facades\Artisan',
    'Mail'            => 'Illuminate\Support\Facades\Mail',
    ...
),

假设我在本地环境中只想覆盖单个提供程序和别名,但保留其他默认值。例如,我想在我的config/local/app.php MailServiceProviderMail外观中进行更改,以仅针对此环境引用其他类。是否可以在我的本地配置文件中再次定义所有提供程序和所有别名(但使用MailServiceProvider和Mail facade的其他值)?

1 个答案:

答案 0 :(得分:1)

最好的方法是使用有条件的加载服务提供商。

您可以在/app/Providers/AppServiceProvider.php文件中执行此操作:

if ($this->app->environment('local')) {
    $this->app->register('App\Providers\LocalErrorHandlerServiceProvider');
} else {
    $this->app->register('App\Providers\ProductionErrorHandlerServiceProvider');
}

第二,但在您的情况下最有效: 您可以创建服务提供商LocalServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class LocalServiceProvider extends ServiceProvider
{

    protected $providers = [
        'Your\Local\ServiceProvider'
    ];
    protected $aliases = [
        'Local' => 'Your\Local\Facade'
    ];
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //register the service providers for local environment
        if ($this->app->isLocal() && !empty($this->providers)) {
            foreach ($this->providers as $provider) {
                $this->app->register($provider);
            }
            //register the alias
            if (!empty($this->aliases)) {
                foreach ($this->aliases as $alias => $facade) {
                    $this->app->alias($alias, $facade);
                }
            }
        }

    }
}

并将其添加到config/app.php以加载:

/*
 * Application Service Providers...
 */
App\Providers\AppServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\LocalServiceProvider::class,

这样,您就可以确定要在LocalServiceProvider类上加载哪些服务提供商和别名。