lysice / hyperf-user-settings
Hyperf 简单用户设置工具。
Requires
- php: >=7.3
- hyperf/framework: >=2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.14
- mockery/mockery: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: >=7.0
- swoole/ide-helper: dev-master
- swow/swow: dev-develop
- symfony/var-dumper: ^5.1
README
Hyperf 简单用户设置工具。设置存储为 JSON 格式在单个数据库列中,因此可以轻松将其添加到现有表(例如 users 表)中。
安装
- 运行
composer require lysice/hyperf-user-settings以将其包含到您的项目中。 - 运行
php bin/hyperf.php vendor:publish lysice/hyperf-use-settings以发布配置文件和迁移文件。 - 运行
php bin/hyperf.php migrate以将字段添加到您的表中。或者,使用此包中包含的 Laravel 迁移文件自动在users表中创建settings列:php bin/hyperf.php migrate。 - 修改位于
config/user-setting.php的已发布配置文件。
配置
存在一个名为 config/user-setting.php 的文件以调整包配置。如果此文件不存在,则运行 php bin/hyperf.php vendor:publish 以创建默认配置文件。
return array( 'table' => 'users', 'column' => 'settings', 'constraint_key' => 'id', 'default_constraint_value' => null, 'custom_constraint' => null, );
表
指定您要使用的数据库表。
列
指定上述表中存储设置 JSON 数据的列。
约束键
指定用于约束的索引列 - 这用于区分不同的用户、对象或模型(通常是 id)。
默认约束值
指定默认约束值 - 默认情况下,这将使用用户的 ID,需要在构造函数中传递 userId,并且将被任何函数调用中指定的 $constraint_value 替换。
自定义约束
为每个查询指定 WHERE 子句 - 如果您不希望访问不同的行(例如,如果您的应用程序仅针对单用户),则设置此值。
用法
使用辅助函数 setting($userId) 初始化 Setting 类,并可以调用 Setting 类中的任何函数。所有函数的 $constraint_value 参数都是可选的;如果没有传递,则将使用配置文件中的 default_constraint_value。
设置
setting($userId)->set('key', 'value', $constraint_value);
使用 set 更改设置的值。如果设置不存在,则会自动创建。您可以通过传递关联数组(key=>value)到第一个参数一次设置多个键。
获取
setting($userId)->get('key', 'default', $constraint_value);
使用 get 获取设置的值。第二个参数是可选的,可以用来指定如果设置不存在时的默认值(默认默认值是 null)。
忘记
setting($userId)->forget('key', $constraint_value);
通过调用 forget 取消设置或删除设置。
存在
setting($userId)->has('key', $constraint_value);
检查设置的是否存在,返回布尔值。
所有
setting($userId)->all($constraint_value);
检索所有设置为关联数组(key=>value)。
保存
setting($userId)->save($constraint_value);
将所有更改保存回数据库。在更改后需要调用此函数;这不是自动的。
加载
setting($userId)->load($constraint_value);
从数据库重新加载设置。如果设置尚未加载就访问或修改,则会自动调用此函数。
调用链
以下函数返回设置对象,因此您可以调用其他函数。例如 set、forget、save。
setting($userId)->set('key', 'value', constraint_value)->get('key', 'default');
示例
以下示例使用默认配置。
使用默认约束值
以下示例设置并返回当前登录用户的设置 "example"。
// Set 'example' setting to 'hello world' and save to db setting($userId)->set('example', 'hello world')->save(); // or use like: $setting = setting($userId); $setting->set('example', 'hello world') $setting->save(); // Get the same setting return setting($userId)->get('example');
最后
贡献
如果您想贡献,请随意创建分支并提交拉取请求。
错误报告
如果您发现有问题,请提交 GitHub 上的问题。