batv45 / laravel-user-settings
为Laravel提供的简单用户设置门面。
Requires
- php: ^7.3|^8.0
- ext-json: *
- illuminate/config: ^8.0|^9.0
- illuminate/database: ^8.0|^9.0
- illuminate/support: ^8.0|^9.0
README
为Laravel提供的简单用户设置门面。设置以JSON格式存储在单个数据库列中,因此您可以轻松地将它添加到现有表(例如users
)中。
安装
- 运行
composer require ricardoboss/laravel-user-settings
将其包含到您的项目中。 - 运行
php artisan vendor:publish --provider="Grimthorr\LaravelUserSettings\ServiceProvider" --tag="config"
以发布配置文件。 - 修改位于
config/laravel-user-settings.php
的已发布配置文件,以符合您的喜好。 - 在您的数据库表中创建一个列以匹配设置文件中的配置。或者,使用此包中包含的Laravel迁移来自动在
users
表中创建一个settings
列:php artisan vendor:publish --provider="Grimthorr\LaravelUserSettings\ServiceProvider" --tag="migrations" && php artisan migrate
。注意:您的列的数据类型应该足够大,以存储所有设置,格式为JSON。对于MySQL,
TEXT
类型应该足够。
配置
打开config/laravel-user-settings.php
以调整包配置。如果此文件不存在,则运行php artisan vendor:publish --provider="Grimthorr\LaravelUserSettings\ServiceProvider" --tag="config"
以创建默认配置文件。
return array( '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上提出问题。
致谢
从Grimthorr fork而来:https://github.com/Grimthorr/laravel-user-settings
部分基于https://github.com/anlutro/laravel-settings。