简体   繁体   中英

Laravel package config does not merge

I am developing several packages and would like to have a single config file for all of them if they are to be published.

Inside my service provider I did this:

public function boot()
{
    $this->publishes([
        __DIR__ . '/config/custom.php' => config_path('custom.php'),
    ]);
}

public function register()
{
    $this->mergeConfigFrom(
        __DIR__ . '/config/custom.php', 'custom'
    );
}

Config:

return [
    'containers' => [
        ...
    ]
];

And surely enough, if I publish it, it creates the file with values inside. But if a file already exists, having different keys:

return [
    'xxxyyy' => [
        ...
    ],
];

publishing doesn't do anything. I would expect it to look like:

return [
    'xxxyyy' => [
        ...
    ],

    'containers' => [
        ...
    ]
];

What am I doing wrong?

In case anyone else is baffled by this, I have tested several cases and here is my explanation ( official docs ).

$this->publishes part enables the package config to be published by vendor:publish command. Nothing to explain here.

$this->mergeConfigFrom part enables the package config to be merged with currently published copy. Merge in this case means merged from Laravel config() scope.

This means that going to artisan tinker and running config('key') (where key is name of your config file) will return nothing if there is no published file and you don't have mergeConfigFrom . If a file is published and has other key value pairs which are not present in your package config and you have mergeConfigFrom present, config('key') will return merged array of values from a published file together with values from your config.

If a file with a same config name exists in your root config folder, and your package internally uses the same config name but you don't have mergeConfigFrom , config('key') will return only contents of a file inside root config folder, and will ignore everything from your package as you didn't provide a way for Laravel to see this as a "global" configuration. Your package will keep internally using the package config, but from app scope you will not be able to fetch it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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