ed-smartass/yii2-settings

A flexible and robust dynamic settings management extension for Yii2 applications with database storage and caching support

Maintainers

Package info

github.com/ed-smartass/yii2-settings

Type:yii2-extension

pkg:composer/ed-smartass/yii2-settings

Statistics

Installs: 80

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

2.1.0 2026-04-13 22:25 UTC

This package is auto-updated.

Last update: 2026-04-13 22:27:33 UTC


README

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.