arthurydalgo/lara-settings

Laravel 的设置。

1.0 2023-04-06 15:14 UTC

This package is not auto-updated.

Last update: 2024-09-17 23:58:38 UTC


README

Laravel 9+ 的基本设置。可以是全局的,也可以转换为模型。

需求

  • PHP >= 8.1
  • Laravel >= 9.0

安装

composer require npabisz/laravel-settings

然后发布供应商资源和迁移

php artisan vendor:publish --provider="Npabisz\LaravelSettings\SettingsServiceProvider"

最后,您应该运行迁移

php artisan migrate

基本用法

use Npabisz\LaravelSettings\Facades\Settings;

// Get global website setting value
$value = Settings::get('api_mode');

// Update global website setting value
Settings::set('api_mode', 'production');

// Access to the Setting model
$settingModel = Settings::setting('api_mode');
$settingModel->delete();

// Get all global website settings models
$settingModels = Settings::all();

// Get all global website settings models,
// but filling the missing ones with default values
$settingModels = Settings::allWithDefaults();

foreach ($settingModels as $setting) {
    if (null === $setting->id) {
        // This one isn't existing in database
        // and has default value based on definition
    }
}

模型范围

use Npabisz\LaravelSettings\Facades\Settings;

// Local scope for model
$model = User::first();
$userSettings = Settings::scope($model);

// Get user setting value
$value = $userSettings->get('is_newsletter_opted_in');

// Set user setting value
$userSettings->set('is_newsletter_opted_in', true);

// You can use any model which implements HasSettings trait
// Local scope for article
$article = Article::first();
$articleSettings = Settings::scope($article);

// Get article setting value
$articleSettings->get('enable_promo_banner');

// Set article setting value
$articleSettings->set('enable_promo_banner', true);

使用全局范围

对于在请求期间不会更改的模型,使用全局范围会更简单,例如,登录用户。默认情况下,它是全局范围,但这里有一个手动执行的例子,例如,您需要在命令中持久化范围。

use Npabisz\LaravelSettings\Facades\Settings;

// Global scope for model
$user = User::first();
Settings::scopeGlobal($user);

// Now you can call magic method and
// it will return SettingsContainer
// for scoped user
Settings::user()->get('is_gamer');
Settings::user()->set('is_gamer', false);

// Replace scope
$anotherUser = User::find(2);
Settings::scopeGlobal($anotherUser);

// Now settings returned by user()
// method belongs to $anotherUser
Settings::user()->set('is_gamer', true);

// You can scope any model which
// has HasSettings trait
$article = Article::first();
Settings::scopeGlobal($article);

// Now you can access them via
// magic method named after class name
Settings::article()->get('is_premium');

设置定义

每个设置都必须有定义。这样它总是同一类型,并且可以具有默认值。设置定义在静态方法 getSettingsDefinitions 下声明。

记住

全局设置在 Setting 模型中定义。

use Npabisz\LaravelSettings\Models\AbstractSetting;

class Setting extends AbstractSetting
{
    /**
     * @return array
     */
    public static function getSettingsDefinitions (): array
    {
        return [
            [
                // Setting name which will be unique
                'name' => 'api_mode',
                // Default value for setting
                'default' => 'sandbox',
                // You can optionally specify valid values
                'options' => [
                    'production',
                    'sandbox',
                ],
            ],
            [
                // Another setting name
                'name' => 'is_enabled',
                // You can optionally specify setting cast
                'cast' => 'bool',
                // Default value for setting
                'default' => false,
            ],
            [
                // Another setting name
                'name' => 'address',
                // You can use classes which will be stored as json
                'cast' => Address::class,
            ],
        ];
    }
}

您可以使用类而不是将地址的每个字段存储在单独的设置中。然后它将被转换为 json。

use Npabisz\LaravelSettings\Models\BaseSetting;

class Address extends BaseSetting
{
    /**
     * @var string 
     */
    public string $street;
    
    /**
     * @var string 
     */
    public string $zipcode;
    
    /**
     * @var string 
     */   
    public string $city;
    
    public function __construct ()
    {
        // You can specify default values
        $this->street = '';
        $this->zipcode = '';
        $this->city = '';
    }
    
    /**
     * This method will be used to populate
     * data from json object.
     * 
     * @param array $data
     */
    public function fromArray (array $data)
    {
        $this->street = $data['street'] ?? '';
        $this->zipcode = $data['zipcode'] ?? '';
        $this->city = $data['city'] ?? '';
    }

    /**
     * @return array
     */
    public function toArray (): array
    {
        return [
            'street' => $this->street,
            'zipcode' => $this->zipcode,
            'city' => $this->city,
        ];
    }
}

模型

如果您想在模型上使用设置,则需要使用 HasSettings 特性并声明一些设置定义。

use Npabisz\LaravelSettings\Traits\HasSettings;

class User extends Authenticatable
{
    use HasSettings;
    
    ...

    /**
     * @return array
     */
    public static function getSettingsDefinitions(): array
    {
        return [
            [
                'name' => 'theme_mode',
                'default' => 'light',
                'options' => [
                    'light',
                    'dark',
                ],
            ],
            [
                'name' => 'is_gamer',
                'cast' => 'bool',
            ],
            [
                'name' => 'games_count',
                'cast' => 'int',
            ],
        ];
    }
}

现在您可以得到它们的设置。

use Npabisz\LaravelSettings\Facades\Settings;

// Assuming user is logged in
Settings::user()->get('is_gamer');
Settings::user()->set('games_count', 10);

// You can also access settings via property
$user->settings->get('is_gamer');
$user->settings->set('games_count', 10);

许可证

npabisz/laravel-settings 在 MIT 许可证下发布。有关详细信息,请参阅附带的 LICENSE