engageinteractive/laravel-config-provider

允许您的用户在运行时更改Laravel包使用的配置文件。

1.2 2023-06-14 15:18 UTC

This package is auto-updated.

Last update: 2024-09-14 18:26:19 UTC


README

Build Status Total Downloads Latest Stable Version License

为了避免Laravel配置文件之间的文件名冲突,使用此包允许您的最终用户更改在您的包中访问的文件。

安装

composer require engageinteractive/laravel-config-provider

现在,在您的包中,创建一个新的 ConfigProvider

namespace Example\Package;

use EngageInteractive\LaravelConfigProvider\ConfigProvider as BaseConfigProvider;

class ConfigProvider extends BaseConfigProvider
{
    /**
     * Key to use when retrieving config values. Override this if you require `Example\Package` to
     * a different file for its configuration.
     *
     * @var string
     */
    protected $configKey = 'example-package';
}

然后,而不是使用 Config 门面,或者在Laravel中使用 config() 函数,您的包应该使用Laravel的服务容器来获取对 ConfigProvider 的访问。

namespace Example\Package;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Prepare the App for your package.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../publishes/config/example-package.php' => config_path('example-package.php'),
        ], 'config');

        // Previous you could have done `config('example-package.enabled')`
        if (app(ConfigProvider::class)->get('enabled')) {
            // Do your thing!
        }
    }
}

这样做将允许您的包的最终用户通过在他们的 AppServiceProvider 中提供一个替代方案来更改您的包使用的文件。

配置文件定制

[使用本节向您的最终用户解释如何定制用于您的包的文件。不要忘记将 example-package.php 重命名为您的,并删除此段落!]

默认情况下,该包使用 config/example-package.php 文件来定义所有配置设置。然而,该包使用 Laravel Config Provider 允许您更改使用的文件。要这样做,请将您自己的 ConfigProvider 实例绑定到您的 AppServiceProvider 中。这在例如 config/example-package.php 已在您的项目中使用的情况下很有用。

首先创建您自己的提供者

namespace App\Config;

use Example\Package\ConfigProvider;

class ExamplePackageConfigProvider extends ConfigProvider
{
    /**
     * Key to use when retrieving config values.
     *
     * @var string
     */
    protected $configKey = 'different-example-package';
}

然后,在启动时添加提供者到绑定。

class AppServiceProvider extends ServiceProvider
{
...

    /**
     * All of the container bindings that should be registered.
     *
     * @var array
     */
    public $bindings = [
        \Example\Package\ConfigProvider::class => \App\Config\ExamplePackageConfigProvider::class,
    ];

...
}

该包仅通过Laravel服务容器使用 ConfigProvider,因此当我们请求它时,您的将被创建。

Laravel 兼容性

适用于Laravel 5.5+。

许可证

Laravel Config Provider 是开源软件,许可协议为 MIT 许可协议