moirei / settings
应用设置的简单解决方案。
1.2.0
2022-09-10 02:29 UTC
Requires
- php: ^8.0
- illuminate/contracts: ^7|^8|^9
- illuminate/support: ^7|^8|^9
- laravel/helpers: ^1.5
- moirei/fields: ^1.1
Requires (Dev)
- illuminate/contracts: ^7|^8|^9
- orchestra/testbench: ^7.5
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.2
- phpunit/phpunit: ^9.5
- thled/pest-plugin-shorthands: ^1.1
This package is auto-updated.
Last update: 2024-09-10 06:54:24 UTC
README
此包是管理 Eloquent 模型设置的简单方法。
此包目前不支持管理全局应用设置。
$notificationsEnabled = $user->settings->get('notifications.enable');
安装
composer require moirei/settings
发布配置
php artisan vendor:publish --tag="model-settings"
用法
转换属性
使用模型的最简单方法是将其转换为设置集合。
use MOIREI\Settings\AsSettingsCollection; use MOIREI\Fields\Inputs\Boolean; ... class User extends Model{ ... protected $casts = [ 'settings' => AsSettingsCollection::class, ]; /** * Get settings configuration (optional) * * @return array */ public function settingsConfig(): array { return [ 'notifications.enable' => Boolean::make('Enable notification')->default(false), ]; } }
对于具有空设置的全新用户模型,应该有默认值。
$user = new User(); $notificationsEnabled = $user->settings->get('notifications.enable'); // Or provide a prefered default $notificationsEnabled = $user->settings->get('notifications.enable', true);
直接访问设置值
$notifications = $this->model->settings->notifications; expect($notifications)->toBeArray();
具有设置特征
为了更方便地访问设置,请将 HasSettings 特征分配给您的模型。
此特征还提供了一个默认的 settingsConfig 方法,该方法从 settings.php 配置中解析默认值。例如,User 模型将期望在配置中的 defaults.users 有默认值。
use MOIREI\Settings\HasSettings; ... class User extends Model{ use HasSettings; ... }
$user = new User(); expect($user->settings())->toBeCollection(); expect($user->settings('notifications.enable'))->toBeBool();
可重用设置
你可以重用设置
class UserSettings extends Settings { /** * @inheritdoc */ public function fields(): array { return [ 'notifications.enable' => Boolean::make('Enable notification')->default(false) ]; } }
在配置中更新
// config/settings.php 'groups' => [ 'users' => \App\Settings\UserSettings::class, ],
现在,您的模型可以指向配置。
class User extends Model{ use HasSettings; // optional if lower-cased pluralised form of class name matches name in groups protected $settingsConfig = 'users'; }
测试
composer test