moirei/settings 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

moirei/settings

Composer 安装命令:

composer require moirei/settings

包简介

A simple solution for application settings.

README 文档

README

This package is a simple approach to managing Eloquent model settings.

This package currently does not support managing global app settings.

$notificationsEnabled = $user->settings->get('notifications.enable');

Installation

composer require moirei/settings

Publish the config

php artisan vendor:publish --tag="model-settings"

Usage

Cast attributes

The simplest way to use the with a model is casting to the settings collection.

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),
        ];
    }
}

New user models with empty settings should have defauls.

$user = new User();
$notificationsEnabled = $user->settings->get('notifications.enable');

// Or provide a prefered default
$notificationsEnabled = $user->settings->get('notifications.enable', true);

Directly access settings values

$notifications = $this->model->settings->notifications;

expect($notifications)->toBeArray();

Has settings trait

For a more function approach to accessing settings, ascribe the HasSettings trait to your model.

This trait also provides a default settingsConfig method that resolves defaults from settings.php config. E.g. the User model will expect defaults in defaults.users of your config.

use MOIREI\Settings\HasSettings;
...
class User extends Model{
    use HasSettings;
    ...
}
$user = new User();
expect($user->settings())->toBeCollection();
expect($user->settings('notifications.enable'))->toBeBool();

Reusable settings

You can reusable settings

class UserSettings extends Settings
{
    /**
     * @inheritdoc
     */
    public function fields(): array
    {
        return [
            'notifications.enable' => Boolean::make('Enable notification')->default(false)
        ];
    }
}

Update in config

// config/settings.php
'groups' => [
   'users' => \App\Settings\UserSettings::class,
],

Now your model can be pointed to the config.

class User extends Model{
    use HasSettings;
    
    // optional if lower-cased pluralised form of class name matches name in groups
    protected $settingsConfig = 'users';
}

Tests

composer test

统计信息

  • 总下载量: 506
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-11-12

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固