vkovic/laravel-settings

轻松保存和检索应用程序特定设置

v0.2.0 2019-01-07 15:39 UTC

This package is auto-updated.

Last update: 2024-09-15 02:06:28 UTC


README

Build Downloads Stable License

轻松地在数据库中持久化应用程序设置

如果您想保存应用程序特定设置,但又不想创建另一个表/模型/逻辑,这个包就是为您准备的。

兼容性

此包与Laravel版本 >= 5.5 兼容

安装

通过composer安装此包

composer require vkovic/laravel-settings

运行迁移以创建用于存储设置的表

php artisan migrate

用法

让我们创建和检索一些设置

// Set setting value as string
Settings::set('foo', 'bar');

// Get setting value
Settings::get('foo'); // : 'bar'

// In case there is no settings found for given key,
// we can pass default value to return
Settings::get('baz', 'default'); // : 'default'

可以使用 query 方法和使用通配符 * 检索多个记录

Settings::set('computer.display.resolution', '1280x1024');
Settings::set('computer.display.brightness', 97);
Settings::set('computer.sound.volume', 54);
Settings::set('computer.mic.volume', 0);

Settings::query('computer.display.*');
// Result:
// [
//     'computer.display.resolution' => '1280x1024',
//     'computer.display.brightness' => 97
// ]

Settings::query('*.sound.*');
// Result:
// [
//     'computer.sound.volume' => 54
// ]

Settings::query('computer.*.volume');
// Result:
// [
//     'computer.sound.volume' => 54,
//     'computer.mic.volume' => 0
// ]

// In case there is no settings found for given query,
// we can pass default value to return
Settings::query('computer.sound.bass', 85); // : 85

除了字符串,设置还可以存储为整数、浮点数、null、布尔值或数组

Settings::set('age', 35);
Settings::set('temperature', 24.7);
Settings::set('value', null);
Settings::set('employed', true);
Settings::set('fruits', ['orange', 'apple']);

Settings::get('age'); // : 35
Settings::get('temperature'); // : 24.7
Settings::get('value', null); // : null
Settings::get('employed'); // : true
Settings::get('fruits'); // : ['orange', 'apple']

我们可以轻松地检查设置是否存在,而无需实际从表中检索它

Settings::set('foo', 'bar');

Settings::exists('foo'); // : true

统计所有设置记录也是轻而易举的

Settings::set('a', 'one');
Settings::set('b', 'two');

Settings::count(); // : 2

如果我们需要所有设置或只是键,没问题

Settings::set('a', 'one');
Settings::set('b', 'two');
Settings::set('c', 'three');

// Get all settings
Settings::all(); // : ['a' => 'one', 'b' => 'two', 'c' => 'three']

// Get only keys
Settings::keys(); // : [0 => 'a', 1 => 'b', 2 => 'c']

此外,我们可以轻松地删除设置

Settings::set('a', 'one');
Settings::set('b', 'two');
Settings::set('c', 'three');

// Remove settings by key
Settings::remove('a');

// Or array of keys
Settings::remove(['b', 'c']);

如果我们出于某种原因想一次性删除所有设置,也没问题

// This will delete all settings!
Settings::purge();

贡献

如果您打算修改此Laravel包,应运行它附带的测试。最简单的方法是使用 Dockerdocker-composephpunit

首先,我们需要初始化Docker容器

docker-compose up -d

然后,我们可以运行测试并查看输出

docker-compose exec app vendor/bin/phpunit