rezkonline/laravel-user-settings

Laravel的简单用户设置门面。

v1.0.1 2022-06-23 03:20 UTC

This package is not auto-updated.

Last update: 2024-09-27 12:18:45 UTC


README

Laravel的简单用户设置门面。设置以JSON格式存储在单个数据库列中,因此您可以轻松将其添加到现有表(例如users)中。

安装

composer require rezkonline/laravel-user-settings

发布配置文件

php artisan vendor:publish --provider="Rezkonline\LaravelUserSettings\ServiceProvider" --tag="config"

公开迁移

php artisan vendor:publish --provider="Rezkonline\LaravelUserSettings\ServiceProvider" --tag="migrations"

迁移已发布的迁移

php artisan migrate

注意:您列的数据类型应该足够大,以便存储所有设置在JSON格式中。对于MySQL,TEXT应该足够。

配置

打开config/laravel-user-settings.php以调整包配置。

return [
  'table' => 'users',
  'column' => 'settings',
  'constraint_key' => 'id',
  'default_constraint_value' => null,
  'custom_constraint' => null,
];

指定您想使用的数据库表。

指定要存储设置JSON数据的上述表中的列。

约束键

指定用于约束的索引列 - 这用于区分不同的用户、对象或模型(通常是id)。

默认约束值

指定默认约束值 - 默认情况下,这将是当前用户的ID,并且可以通过在函数调用中指定任何$constraint_value来覆盖。

自定义约束

指定每个查询的where子句 - 如果您不想访问不同的行(例如,如果您的应用程序仅限单用户),则设置此值。

使用方法

使用设置门面(Setting::)或辅助函数(setting()->)来访问此包中的方法。所有函数的$constraint_value参数都是可选的;如果没有传递,则将从配置文件中使用的default_constraint_value

设置

Setting::set('key', 'value', $constraint_value);
setting()->set('key', 'value', $constraint_value);

使用set来更改设置的值。如果设置不存在,它将被自动创建。您可以通过将关联(key=>value)数组传递给第一个参数一次性设置多个键。

获取

Setting::get('key', 'default', $constraint_value);
setting()->get('key', 'default', $constraint_value);
setting('key', 'default', $constraint_value);

使用get来检索设置的值。第二个参数是可选的,如果设置不存在,可以用来指定默认值(默认默认值是null)。

删除

Setting::forget('key', $constraint_value);
setting()->forget('key', $constraint_value);

通过调用forget来取消设置或删除设置。

存在

Setting::has('key', $constraint_value);
setting()->has('key', $constraint_value);

检查设置是否存在,返回布尔值。

全部

Setting::all($constraint_value);
setting()->all($constraint_value);

以关联数组(key=>value)的形式检索所有设置。

保存

Setting::save($constraint_value);
setting()->save($constraint_value);

将所有更改保存回数据库。在做出更改后,需要调用此函数;这不是自动的。

加载

Setting::load($constraint_value);
setting()->load($constraint_value);

从数据库重新加载设置。如果设置在访问或修改之前尚未加载,则自动调用此函数。

示例

以下示例使用默认配置。

使用默认约束值

以下示例设置并返回当前登录用户的设置"example"。

// Set 'example' setting to 'hello world'
Setting::set('example', 'hello world');

// Save to database
Setting::save();

// Get the same setting
return Setting::get('example');

指定约束值

以下示例设置并返回ID为23的用户设置"example"。

// Set 'example' setting to 'hello world'
Setting::set('example', 'hello world', 23);

// Save to database
Setting::save(23);

// Get the same setting
return Setting::get('example', null, 23);

最后

贡献

如果您想做出贡献,请随意创建分支并提交拉取请求。

错误报告

如果您发现有问题,请通过GitHub提出问题。

鸣谢

基于 https://github.com/ricardoboss/laravel-user-settings 分支,并且参考了 https://github.com/anlutro/laravel-settings