emadha/laravel-dynamic-config

该软件包使用户能够将配置文件存储在数据库表中,从而更容易从UI中自定义这些值。

v1.0.4 2022-02-11 00:42 UTC

This package is auto-updated.

Last update: 2024-09-11 06:23:12 UTC


README

介绍

该软件包使用户能够将配置文件存储在数据库表中,从而更容易从UI中自定义这些值。

安装

您可以通过composer安装此软件包

composer require emadha/laravel-dynamic-config

该软件包将自动注册自己。

您可以使用以下命令发布配置

配置文件

php artisan vendor:publish --provider="EmadHa\DynamicConfig\ServiceProvider" --tag="config"

迁移

php artisan vendor:publish --provider="EmadHa\DynamicConfig\ServiceProvider" --tag="migrations"

使用方法

首先,您需要决定将哪些配置文件存储在数据库中,只需在文件中添加'dynamic'=> true即可,就这么简单

# /config/app.php 
return [
    'dynamic' => true,
     ...
];
  • 注意,dynamic指示符定义在/config/emadha/dynamic-conf.php
  • 您可以将dynamic=>true添加到任何配置文件中,将其存储在数据库中,并从那里获取值,而不是使用实际的配置文件
  • 默认值将来自实际的配置文件。
  • 您可以动态加载多个配置文件。
  • dynamic=>true只能添加到配置数组的第一个维度中。

此软件包的主要配置文件位于/config/emadha/dynamic-conf.php,包含以下代码

<?php
return [
    /* The Config database table name */
    'table'                   => 'confs',

    /*
     * The key that defines which config file should be loaded dynamically
     * and store into the database
     * Add that key to any config file to make it dynamic.
     */
    'dynamic_key'             => 'dynamics',

    /*
     * they key which will have the defaults of a config key
     * example: config('defaults.app.name'); This is added on runtime.
     */
    'defaults_key'            => 'defaults',

    /*
     * Delete orphan keys
     * if set to true and delete a key from the actual config file,
     * that key will be deleted from database.
     */
    'auto_delete_orphan_keys' => true,
];

该文件的内容非常清晰且具有很好的文档说明。

使用方法

dd(config('app.name')); // Will return a Model object for that db row (key)
echo config('app.name'); // Will get the value from a config key using __toString() method from the DynamicConfig Model;
config('app.name')->setTo('Some New Value'); // will update that config key in database
config('app.name')->default(); // Will return the default value of that key (from the actual config file and not from the database)
config('app.name')->revert(); // Will revert the key value in database back to default (to what it is in the actual config file) 

就这么简单。

为什么这很有用?

如果您想以动态方式从UI(后端、前端)控制网站标题,而不需要编辑实际的配置文件,那么这是一个很好的方法。

另一个例子:假设您有一个Google分析代码和一些其他自定义设置,这些都在/config/site.php中如下所示

# /config/site.php
return [
    'dynamic'=>true,
    'title'=>config('app.name'),
    'description'=>'My Site Meta Description',
    'google'=>[
        'UA'=>'UA-XXXXXXXX-X',
        'enabled'=>true,
    ],
];

此配置文件无法从用户界面轻松修改,因此您的客户无法编辑此文件,在这种情况下,此软件包将非常有用,将dynamic=>true键添加到该配置文件中,将使其以与Laravel相同的格式将其值存储在数据库中,因此获取该配置文件中某些键的值对您来说不会有任何区别,例如config('site.google.UA'),还可以添加一些很棒的功能,如更新值和还原到默认值。

使用这种方法,您现在可以创建一个后端输入来自定义这些,只需一行代码config('site.google.UA')->setTo('XYZ');然后在您的blade中像平常一样使用它

{{-- welcome.blade.php--}}
<title>{{ config('site.title') }}</title>
<script>// Analytics ID: {{ config('site.google.UA')}}</script>