ed-smartass/yii2-settings A flexible and robust dynamic settings management extension for Yii2 applications with database storage and caching support

Yii2 Settings ΒΆ

  1. Features
  2. Installation
  3. Configuration
  4. Usage
  5. API Reference
  6. Supported Types
  7. Testing
  8. License

Dynamic key-value settings for Yii2 with database storage, automatic type casting, and caching.

Русская вСрсия

Latest Stable Version Total Downloads License

Features ΒΆ

  • Database-backed key-value storage
  • Five value types: integer, float, string, boolean, array (JSON)
  • Automatic type detection on write, strict type casting on read
  • Optional caching with DbDependency auto-invalidation
  • Magic property access: $settings->key to read/write
  • Config placeholders: inject settings into component configs via %setting.name|default%
  • Works with any RDBMS supported by Yii2 (MySQL, PostgreSQL, SQLite, etc.)
  • PHP 7.3+ and PHP 8.x compatible

Installation ΒΆ

composer require ed-smartass/yii2-settings

Run the migration:

php yii migrate --migrationPath=@vendor/ed-smartass/yii2-settings/src/migrations

Or register the migration path in console config:

return [
    'controllerMap' => [
        'migrate' => [
            'class' => 'yii\console\controllers\MigrateController',
            'migrationPath' => [
                '@console/migrations',
                '@vendor/ed-smartass/yii2-settings/src/migrations',
            ],
        ],
    ],
];

Configuration ΒΆ

return [
    'components' => [
        'settings' => [
            'class' => 'Smartass\Yii2Settings\Settings',

            // Table name. Default: '{{%setting}}'
            'table' => '{{%setting}}',

            // DB connection component ID. Default: 'db'
            'db' => 'db',

            // Cache component ID, or null to disable caching. Default: 'cache'
            'cache' => 'cache',

            // Cache key prefix. Default: 'settings'
            'cacheKey' => 'settings',

            // Cache TTL in seconds, null = no expiration. Default: null
            'cacheDuration' => null,

            // Replace %placeholders% in component configs. Default: false
            'processConfig' => false,
        ],
    ],
];

Usage ΒΆ

Basic operations ΒΆ
$settings = Yii::$app->settings;

// Set
$settings->set('site.name', 'My App');
$settings->set('per_page', 25);
$settings->set('maintenance', false);
$settings->set('mail.providers', ['smtp', 'sendmail']);

// Get
$settings->get('site.name');                    // 'My App'
$settings->get('missing_key');                  // null
$settings->get('missing_key', 'fallback');      // 'fallback'
$settings->get('theme', 'default', true);       // 'default' (also saved to DB)

// Delete
$settings->delete('site.name');

// Delete all
$settings->flush();

// Force reload from database
$settings->refresh();

// Get all settings as array
$settings->settings; // ['per_page' => 25, 'maintenance' => false, ...]
Magic property access ΒΆ

Magic properties work for keys that are valid PHP identifiers (e.g. site_name). Keys containing dots or hyphens (e.g. site.name, smtp-host) require get()/set() or brace syntax.

// Read / write simple keys
$name = Yii::$app->settings->site_name;
Yii::$app->settings->site_name = 'New Name';

// Dot / hyphen keys β€” use get()/set() or brace syntax
$host = Yii::$app->settings->get('mail.smtp-host');
Yii::$app->settings->set('mail.smtp-host', 'smtp.example.com');
$host = Yii::$app->settings->{'mail.smtp-host'};
Explicit type override ΒΆ

By default the type is detected automatically. You can force a specific type:

use Smartass\Yii2Settings\Settings;

// Store numeric string as integer
$settings->set('port', '8080', Settings::TYPE_INTEGER);

// Store integer as string
$settings->set('code', 42, Settings::TYPE_STRING);
Config placeholders ΒΆ

Enable processConfig and add the component to bootstrap so the event handler is registered at application start:

// app config
return [
    'bootstrap' => ['settings'],
    'components' => [
        'settings' => [
            'class' => 'Smartass\Yii2Settings\Settings',
            'processConfig' => true,
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => '%mail.host|smtp.example.com%',  // setting name | default
                'port' => '%mail.port%',                    // setting name (no default)
            ],
        ],
    ],
];

Syntax: %setting.name|default_value% or %setting.name%

API Reference ΒΆ

get($key, $default = null, $saveDefault = false) ΒΆ

Returns the value for $key, or $default if not found. When $saveDefault is true, the default value is persisted to the database.

set($key, $value, $type = null) ΒΆ

Creates or updates a setting. Passing null as $value deletes the setting. The $type parameter accepts one of the Settings::TYPE_* constants; when omitted, the type is detected automatically.

delete($key) ΒΆ

Deletes a setting by key.

flush() ΒΆ

Deletes all settings.

refresh() ΒΆ

Clears the in-memory cache and invalidates the cache entry, forcing the next read to hit the database.

Property: $settings ΒΆ

Returns all settings as an associative array ['key' => value, ...].

Supported Types ΒΆ

Type Constant PHP type Storage
integer Settings::TYPE_INTEGER int String representation
float Settings::TYPE_FLOAT float String representation
string Settings::TYPE_STRING string As-is
boolean Settings::TYPE_BOOLEAN bool 0 / 1
array Settings::TYPE_ARRAY array JSON

Testing ΒΆ

composer install
vendor/bin/phpunit

License ΒΆ

MIT. See LICENSE.

0 0
1 follower
80 downloads
Yii Version: 2.0
License: MIT
Category: Database
Developed by: ed-smartass ed-smartass
Created on: Aug 28, 2021
Last updated: (not set)
Packagist Profile
Github Repository

Related Extensions