nabcellent / laraconfig
Laravel 的按用户设置仓库系统
Requires
- php: ^8.3
- illuminate/cache: ^11.0
- illuminate/collections: ^11.0
- illuminate/config: ^11.0
- illuminate/database: ^11.0
- illuminate/support: ^11.0
- symfony/console: ^7.1
Requires (Dev)
- mockery/mockery: ^1.6
- orchestra/testbench: ^9.2
- phpunit/phpunit: ^11.2
README
此包的原始来源已被存档。
我正在努力维持它。😃
Laraconfig
Laravel 的按用户设置仓库系统。
此包允许用户拥有可查询、更改和甚至轻松快速更新的设置。
User::find(1)->settings->set('color', 'red');
要求
- Laravel ^11
- PHP ^8.3
工作原理
Laraconfig 通过扩展 Laravel 关系并包含一个迁移系统来管理它们。
每个设置只是一个值,并引用一个包含类型和名称等信息的父 "元数据",同时与用户相关联。
由于 Laraconfig 在幕后使用 Eloquent ORM,因此获取一个或所有设置对开发人员来说是完全透明的。
快速入门
您可以通过 composer 安装此包。
composer require nabcellent/laraconfig
首先,发布并运行迁移。这些迁移将添加两个表,分别称为 user_settings 和 user_settings_metadata。一个存储每个用户的值,另一个存储设置的元数据。
php artisan vendor:publish --provider="Nabcellent\Laraconfig\LaraconfigServiceProvider" --tag="migrations"
php artisan migrate
迁移使用一个形态列来连接到用户。您可以在迁移之前更改它。
其次,将 HasConfig 特性添加到您想要设置设置的 User 模型中。
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Nabcellent\Laraconfig\HasConfig; class User extends Authenticatable { use HasConfig; // ... }
最后,使用 settings:publish artisan 命令。这将创建一个位于项目根目录中的 settings 文件夹和一个 users.php 文件。
php artisan settings:publish
现在,让我们创建一些设置。
设置清单
Laraconfig 通过一种类型的清单来管理全局用户设置,即 settings/users.php 文件。您将看到已经编写好的示例设置。
use Nabcellent\Laraconfig\Facades\Setting; Setting::name('color')->string();
创建设置
要创建设置,请使用 Setting 外观。您可以从设置名称开始,名称必须是唯一的,然后声明类型。
use Nabcellent\Laraconfig\Facades\Setting; Setting::name('dark_mode')->boolean();
Laraconfig 与 7 种类型的设置兼容,模仿它们的 PHP 原生类型,以及 Collection 和 Datetime (Carbon) 对象。
array()boolean()collection()datetime()float()integer()string()
数组和集合在数据库中序列化为 JSON。
默认值
所有设置都有一个默认值 null,但您可以使用 default() 方法设置不同的初始值。
use Nabcellent\Laraconfig\Facades\Setting; Setting::name('color')->string()->default('black');
您可以使用
setDefault()将值恢复到默认值。
启用或禁用
默认情况下,所有设置都是启用的,但您可以使用 disabled() 修改此设置。
Setting::name('color')->disabled();
启用或禁用是表示性的;禁用的设置仍然可以更新。您可以使用
setIfEnabled()编程式地设置值。
分组设置
您可以将设置名称设置为一个组。当您希望在前端按顺序显示设置时,这可能很有用。
Setting::name('color')->group('theme');
包
当 Laraconfig 迁移新的设置时,这些设置将创建到所有模型中。您可以通过 "包" 过滤给定的一组设置。
默认情况下,所有设置都创建在 users 包下,但您可以使用 bag() 方法为任何内容更改默认包。
Setting::name('color')->group('theme')->bag('style'); Setting::name('notify_email')->boolean()->default(true)->bag('notifications'); Setting::name('notify_sms')->boolean()->default(false)->bag('notifications');
稍后,在您的模型中,您可以使用 filterBags() 在模型中过滤您想要处理的包。
设置迁移
创建设置完成后,您应该使用settings:migrate命令,让Laraconfig将设置元数据添加到您的数据库中。
php artisan settings:migrate
在幕后,Laraconfig会查找使用HasConfig特性的模型,并根据清单上的信息相应地填充设置。
迁移只能向前执行。一旦完成迁移,就无法回滚。在生产环境中,删除设置需要确认。
添加新设置
只需创建一个新的设置并运行settings:migrate。现有的设置不会再次创建,因为Laraconfig在执行之前会检查其是否存在。
use Nabcellent\Laraconfig\Facades\Setting; Setting::name('color')->string()->default('black'); // This new setting will be created Setting::name('notifications')->boolean()->default(true);
删除旧设置
要删除旧设置,只需删除其声明并运行settings:migrate。Laraconfig会将声明的设置与数据库中创建的设置进行比较,并在迁移执行结束时删除那些在清单中不再存在的设置。
use Nabcellent\Laraconfig\Facades\Setting; // Commenting this line will remove the "color" setting on migration. // Setting::name('color')->string()->default('black'); // This new setting will be created Setting::name('notifications')->boolean()->default(true);
由于此过程可能很危险,生产环境中需要确认。
升级设置
您不需要直接进入数据库来更新设置。相反,只需直接在清单中更改设置属性。Laraconfig将相应地更新元数据。
假设我们有一个“颜色”设置,我们希望将其从字符串更新为数组颜色,并具有默认值和组。
Setting::name('color')->string()->bag('theme'); // This is the new declaration. // Setting::name('color') // ->array() // ->default(['black']) // ->group('theme');
Laraconfig将检测新更改,并更新元数据,同时保留用户的值。
// This is the old declaration. // Setting::name('color')->string()->bag('theme'); Setting::name('color') ->array() ->default(['black']) ->group('theme');
只有在迁移时间设置与之前不同的情况下,才会更新。
完成之后,我们可以使用settings:migrate将旧设置迁移到新设置。用户将保持他们之前相同的设置值,但...如果我们还希望更改每个用户的值呢?我们可以使用using()方法将每个用户的设置传递给一个回调函数,该回调函数将返回新的值。
Setting::name('color') ->array() ->default('black') ->group('theme') ->using(fn ($old) => $old->value ?? 'black'); // If the value is null, set it as "black".
using()方法只有在设置在迁移时间与之前不同的情况下才会运行。
在幕后,Laraconfig将查找“颜色”设置,更新元数据,然后使用lazy()查询通过回调更新值。
如果您有数十万条记录,建议直接在数据库上迁移,因为这种方法比直接SQL语句更安全,但速度较慢。
迁移到新设置
在其他情况下,您可能希望将设置迁移到全新的设置。在两种情况下,您都可以使用from()来获取要迁移的旧设置值,如果想要更新每个用户的值,可以使用using()。
以上面相同的例子为例,我们将“颜色”设置迁移到简单的“深色主题”设置。
// This old declaration will be deleted after the migration ends. // Setting::name('color')->string()->bag('theme'); // This is a new setting. Setting::name('dark') ->boolean() ->default(false) ->group('theme') ->from('color') ->using(static fn ($old) => $old->value === 'black'); // If it's black, then it's dark.
from和using只在迁移时间旧设置存在时执行。
在幕后,Laraconfig首先创建新的“主题”设置,然后查找数据库中的旧“颜色”设置,将旧值转换为新值。由于旧设置不在清单中,它将从数据库中删除。
管理设置
Laraconfig像处理任何Eloquent Morph-Many 关系一样处理设置,但功能更强大。
只需在您的模型上使用settings属性。这个属性就像您的普通Eloquent Collection,因此您可以访问所有其工具。
$user = User::find(1); echo "Your color is: {$user->settings->get('color')}.";
使用
settings是首选的,因为它只会加载一次设置。
初始化
默认情况下,HasConfig特性将在通过Eloquent ORM成功创建用户后,在数据库中创建一个新的设置包,因此您不需要创建任何设置。
如果您想手动处理初始化,可以使用 shouldInitializeConfig() 方法并返回 false,这在程序化初始化设置时很有用。
// app/Models/User.php /** * Check if the user should initialize settings automatically after creation. * * @return bool */ protected function shouldInitializeConfig(): bool { // Don't initialize the settings if the user is not verified from the start. // We will initialize them only once the email is properly verified. return null !== $this->email_verified_at; }
由于上述示例中的用户将不会初始化,我们必须手动使用 initialize() 方法。
// Initialize if not initialized before. $user->settings()->initialize(); // Forcefully initialize, even if already initialized. $user->settings()->initialize(true);
检查设置初始化
您可以使用 isInitialized() 检查用户配置是否已初始化。
if ($user->settings()->isInitialized()) { return 'You have a config!'; }
检索设置
您可以通过名称轻松获取设置的值,这使得所有操作都变成了一个美丽的 单行代码。
return "Your favorite color is {$user->settings->color}";
由于这仅支持字母数字和下划线字符,您可以使用 value()。
return "Your favorite color is {$user->settings->value('color')}";
您还可以使用 get() 获取底层设置模型。如果设置不存在,它将返回 null。
$setting = $user->settings->get('theme'); echo "You're using the [$setting->value] theme.";
由于 settings 是一个 集合,您可以访问所有的好东西,如迭代
foreach ($user->settings as $setting) { echo "The [$setting->name] has the [$setting->value] value."; }
您还可以使用 only() 方法通过名称返回设置集合,或者使用 except() 获取除了指定的以外的所有设置。
$user->settings->only('colors', 'is_dark'); $user->settings->except('dark_mode');
分组设置
由于设置列表是一个集合,您可以使用 groups() 方法按所属组的名称分组。
$user->settings->groups(); // or ->groupBy('group')
请注意,设置默认情况下被分组到
default组(不是字面意思)。
设置值
通过指定设置名称和值,可以轻松地设置值。
$user->settings->color = 'red';
由于这仅支持由字母数字和下划线组成的设置名称,您还可以通过指定设置名称使用 set() 方法设置值。
$user->settings->set('color-default', 'red');
或者,您可以直接在模型本身中直接进入纯种模式。
$setting = $user->settings->get('color'); $setting->value = 'red'; $setting->save();
当使用 set() 一次性设置多个设置时,您可以使用数组,这在处理 验证返回的数组 时很有用。
$user->settings->set([ 'color' => 'red', 'dark_mode' => false, ]);
当 使用缓存 时,任何更改都会立即使缓存失效,并在集合被垃圾回收之前排队重新生成。
话虽如此,直接将设置更新到数据库 不会重新生成缓存。
设置默认值
您可以使用设置实例或使用 settings 属性上的 setDefault() 将设置还原到默认值。
$setting = $user->settings->get('color'); $setting->setDefault(); $user->settings->setDefault('color');
如果设置没有默认值,将使用
null。
检查 null
使用 isNull() 和设置名称检查是否设置了 null 值。
if ($user->settings->isNull('color')) { return 'The color setting is not set.'; }
禁用/启用设置
出于表现目的,所有设置默认启用。您可以使用 enable() 和 disable() 分别启用或禁用设置。要检查设置是否启用,请使用 isEnabled() 方法。
$user->settings->enable('color'); $user->settings->disable('color');
禁用的设置仍然可以设置。如果您只想在启用时设置值,请使用
setIfEnabled()。$user->settings->setIfEnabled('color', 'red');
设置包
Laraconfig 使用一个名为 default 的单个包。如果您在清单中声明了不同的包集,您可以使用 filterBags() 方法创建一个只使用特定包集的模型,该方法应返回包名称(或名称)。
// app/Models/User.php
i
这将在从数据库检索设置时应用过滤器。这使得在用户具有不同的角色或属性或程序化时轻松切换包。
所有 设置都是为所有具有
HasConfig特性的模型创建的,无论模型使用的包是什么。
禁用包过滤器范围
Laraconfig 对查询应用一个过滤器以排除模型包之外的设置。虽然这简化了开发,但有时您将想要与可用的所有设置一起工作。
禁用袋过滤器有两种方法。第一种相对简单:只需在查询时使用withoutGlobalScope(),这将允许查询用户可用的所有设置。
use Nabcellent\Laraconfig\Eloquent\Scopes\FilterBags; $allSettings = $user->settings()->withoutGlobalScope(FilterBags::class)->get();
如果您需要一个更永久的解决方案,只需在您的模型中使用filterBags()方法时返回一个空数组或null即可,这将完全禁用作用域。
/** * Returns the bags this model uses for settings. * * @return array|string */ public function filterBags(): array|string|null { return null; }
缓存
每次请求都击中数据库以检索用户设置,如果预计会发生很多,可能会产生负面影响。为了避免这种情况,您可以激活一个缓存,每次设置更改时都会重新生成。
缓存实现避免了数据竞争。它仅针对最后更改的数据重新生成缓存,因此如果有两个或多个进程尝试将某些内容保存到缓存中,只有最新数据将被持久化。
启用缓存
您可以通过将LARACONFIG_CACHE环境变量设置为true轻松启用缓存,并使用非默认缓存存储(如Redis)与LARACONFIG_STORE一起使用。
LARACONFIG_CACHE=true LARACONFIG_STORE=redis
或者,检查
laraconfig.php文件以自定义缓存TTL和前缀。
管理缓存
您可以使用regenerate()强制重新生成单个用户的缓存。这基本上是将现有的设置保存到缓存中。
$user->settings->regenerate();
您还可以使用invalidate()无效化缓存的设置,这将从缓存中删除条目。
$user->settings->invalidate();
最后,您可以设置regeneratesOnExit为true以获得一些安慰,这样PHP进程垃圾回收设置时将重新生成缓存。
$user->settings->regeneratesOnExit = true;
您可以在配置文件中禁用自动重新生成。
迁移时重新生成缓存
如果缓存已激活,迁移将在完成后为每个用户无效化设置缓存。
根据缓存系统,忘记每个缓存键可能会产生负面影响。相反,您可以使用--flush-cache命令来刷新Laraconfig使用的缓存存储,而不是逐个删除每个键。
php artisan settings:migrate --flush-cache
由于这将删除缓存中的所有数据,因此建议为Laraconfig使用一个专用的缓存存储,如单独的Redis数据库。
验证
设置值会被转换,但不会被验证。您应该在应用程序中验证您计划存储在设置中的每个值。
use App\Models\User; use Illuminate\Http\Request; public function store(Request $request, User $user) { $settings = $request->validate([ 'age' => 'required|numeric|min:14|max:100', 'color' => 'required|string|in:red,green,blue' ]); $user->settings->setIfEnabled($settings); // ... }
测试
最终,您将面临为每个创建的用户创建设置和元数据的问题。您可以在创建用户之前直接在数据库中创建元数据,除非您已禁用初始化。
public function test_user_has_settings(): void { Metadata::forceCreate([ 'name' => 'foo', 'type' => 'string', 'default' => 'bar', 'bag' => 'users', 'group' => 'default', ]); $user = User::create([ // ... ]); // ... }
安全
如果您发现任何与安全相关的问题,请通过Nabcellent@gmail.com发送电子邮件,而不是使用问题跟踪器。
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。