cryental / laravel-dynamic-config
本软件包允许用户将配置文件存储在数据库表中,从而更易于从用户界面中自定义这些值。
1.1
2024-05-30 12:52 UTC
Requires
- laravel/framework: ^7.0|^8.0|^9.0|^10.0|^11.0
This package is auto-updated.
Last update: 2024-09-30 13:27:40 UTC
README
简介
本软件包允许用户将配置文件存储在数据库表中,从而更易于从用户界面中自定义这些值。
安装
您可以通过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)
就这么简单。
这有什么用呢?
如果您想以动态的方式控制网站标题,从用户界面(后端、前端)进行控制,而不需要编辑实际的配置文件,那么这是一个好的方法。
另一个例子:假设您有一个谷歌分析代码和一些其他自定义设置,它们在/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>