yii2tech/config

此包已被弃用且不再维护。未建议替代包。

提供对Yii2应用运行时配置的支持

资助包维护!
klimov-paul
Patreon

安装次数: 29,280

依赖者: 2

建议者: 0

安全: 0

星标: 58

关注者: 9

分叉: 11

开放问题: 2

类型:yii2-extension

1.0.7 2019-01-24 15:18 UTC

This package is auto-updated.

Last update: 2022-01-10 10:47:20 UTC


README

12951949

为Yii 2的应用程序运行时配置扩展


此扩展提供对应用程序运行时配置的支持,从数据库加载配置。

有关许可信息,请检查LICENSE文件。

Latest Stable Version Total Downloads Build Status

安装

安装此扩展的首选方式是通过composer

运行

php composer.phar require --prefer-dist yii2tech/config

或将其添加到您的composer.json文件的要求部分。

"yii2tech/config": "*"

使用

此扩展允许使用从外部存储(如关系型数据库、MongoDB等)组成的配置重新配置已创建的Yii应用程序实例。它允许重新配置任何应用程序属性、组件或模块。配置是通过[[\yii2tech\config\Manager]]组件执行的,该组件应添加到应用程序配置中。例如

[
    'bootstrap' => [
        'configManager',
        // ...
    ],
    'components' => [
        'configManager' => [
            'class' => 'yii2tech\config\Manager',
            'items' => [
                'appName' => [
                    'path' => 'name',
                    'label' => 'Application Name',
                    'rules' => [
                        ['required']
                    ],
                ],
                'nullDisplay' => [
                    'path' => 'components.formatter.nullDisplay',
                    'label' => 'HTML representing not set value',
                    'rules' => [
                        ['required']
                    ],
                ],
            ],
        ],
        ...
    ],
];

[[\yii2tech\config\Manager]]实现了[[\yii\base\BootstrapInterface]]接口,因此将其放在'bootstrap'部分将应用运行时配置。您可以使用以下代码手动将配置应用于应用程序或任何[[\yii\base\Module]]后代

$configManager = Yii::$app->get('configManager');
$configManager->configure(Yii::$app);

配置项规范

需要重新配置的应用程序部分由[[\yii2tech\config\Manager::$items]]确定,它是一个[[\yii2tech\config\Item]]的列表。每个配置项都确定配置路径 - 应用程序配置数组中指向目标值的键的列表。例如:路径'components.formatter.nullDisplay'(或['components', 'formatter', 'nullDisplay'])指向[[\yii\i18n\Formatter]]组件的'nullDisplay'属性,路径'名称'指向[[\yii\base\Application::name]]等等。

注意:如果没有指定路径,则被视为[[\yii\base\Module::$params]]数组中的键,它与配置项ID([[\yii2tech\config\Manager::$items]]数组中键的名称)匹配。

配置项还可以有多个属性,支持创建配置设置的Web界面。这些是

  • 'label' - 字符串,输入标签。
  • 'description' - 字符串,配置参数描述或输入提示。
  • 'rules' - 数组,值验证规则。
  • 'inputOptions' - 数组,任何其他输入选项的列表。

以下是项目规范的一些示例

'appName' => [
    'path' => 'name',
    'label' => 'Application Name',
    'rules' => [
        ['required']
    ],
],
'nullDisplay' => [
    'path' => 'components.formatter.nullDisplay',
    'label' => 'HTML representing not set value',
    'rules' => [
        ['required']
    ],
],
'adminEmail' => [
    'label' => 'Admin email address',
    'rules' => [
        ['required'],
        ['email'],
    ],
],
'adminTheme' => [
    'label' => 'Admin interface theme',
    'path' => ['modules', 'admin', 'theme'],
    'rules' => [
        ['required'],
        ['in', 'range' => ['classic', 'bootstrap']],
    ],
    'inputOptions' => [
        'type' => 'dropDown',
        'items' => [
            'classic' => 'Classic',
            'bootstrap' => 'Twitter Bootstrap',
        ],
    ],
],

提示:由于运行时配置可能包含许多项目,并且它们的声明可能需要大量代码,因此可以将它们移动到单独的文件中,并通过此文件名指定。

配置存储

声明的配置项可以保存到持久存储中,然后从中检索。实际的项目存储是通过[[\yii2tech\config\Manager::storage]]确定的。

以下存储方式可供选择

  • [[\yii2tech\config\StoragePhp]] - 在PHP文件中存储配置
  • [[\yii2tech\config\StorageDb]] - 在关系型数据库中存储配置
  • [[\yii2tech\config\StorageMongoDb]] - 在MongoDB中存储配置
  • [[\yii2tech\config\StorageActiveRecord]] - 使用ActiveRecord查找配置

请参考特定存储类以获取更多详细信息。

创建配置Web界面

此扩展最常用的场景是创建一个Web界面,允许在运行时控制应用程序配置。[[\yii2tech\config\Manager]]不仅用于应用配置的应用,它还帮助创建配置编辑的界面。

配置管理的Web控制器可能如下所示

use yii\base\Model;
use yii\web\Controller;
use Yii;

class ConfigController extends Controller
{
    /**
     * Performs batch updated of application configuration records.
     */
    public function actionIndex()
    {
        /* @var $configManager \yii2tech\config\Manager */
        $configManager = Yii::$app->get('configManager');

        $models = $configManager->getItems();

        if (Model::loadMultiple($models, Yii::$app->request->post()) && Model::validateMultiple($models)) {
            $configManager->saveValues();
            Yii::$app->session->setFlash('success', 'Configuration updated.');
            return $this->refresh();
        }

        return $this->render('index', [
            'models' => $models,
        ]);
    }

    /**
     * Restores default values for the application configuration.
     */
    public function actionDefault()
    {
        /* @var $configManager \yii2tech\config\Manager */
        $configManager = Yii::$app->get('configManager');
        $configManager->clearValues();
        Yii::$app->session->setFlash('success', 'Default values restored.');
        return $this->redirect(['index']);
    }
}

主要视图文件可以是以下

<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $models yii2tech\config\Item[] */
?>
<?php $form = ActiveForm::begin(); ?>

<?php foreach ($models as $key => $model): ?>
    <?php
    $field = $form->field($model, "[{$key}]value");
    $inputType = ArrayHelper::remove($model->inputOptions, 'type');
    switch($inputType) {
        case 'checkbox':
            $field->checkbox();
            break;
        case 'textarea':
            $field->textarea();
            break;
        case 'dropDown':
            $field->dropDownList($model->inputOptions['items']);
            break;
    }
    echo $field;
    ?>
<?php endforeach;?>

<div class="form-group">
    <?= Html::a('Restore defaults', ['default'], ['class' => 'btn btn-danger', 'data-confirm' => 'Are you sure you want to restore default values?']); ?>
    &nbsp;
    <?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

独立配置

[[\yii2tech\config\Manager]]不仅可以用于应用配置存储:它可以存储任何独立任务的具体配置集。您可以将管理器配置为应用程序组件,存储一些用户设置并使用它来检索。例如

[
    'components' => [
        // no application boostap!
        'userInterfaceConfig' => [
            'class' => 'yii2tech\config\Manager',
            'storage' => [
                'class' => 'yii2tech\config\StorageDb',
                'autoRestoreValues' => true, // restore config values from storage at component initialization
                'filter' => function () {
                    return [
                        'userId' => Yii::$app->user->id // vary storage records by user
                    ];
                },
            ],
            'items' => [
                'sidebarEnabled' => [
                    'value' => true, // default value
                    'rules' => [
                        ['boolean']
                    ],
                ],
                'backgroundColor' => [
                    'value' => '#101010', // default value
                    'rules' => [
                        ['required']
                    ],
                ],
                // ...
            ],
        ],
        ...
    ],
];

Then you can retrieve any user setting via created component:

```php
if (Yii::$app->userInterfaceConfig->getItemValue('sidebarEnabled')) {
    // render sidebar
}

echo Yii::$app->userInterfaceConfig->getItemValue('backgroundColor');

请注意,您应该启用[[\yii2tech\config\Manager::$autoRestoreValues]]以使配置值能够自动从持久存储中恢复,否则您必须手动调用[[\yii2tech\config\Manager::restoreValues()]]方法。另外,不要忘记为每个配置项指定默认值,否则它将从中当前应用程序获取。

您还可以使用[[\yii2tech\config\Manager]]来配置特定组件。例如

use yii\base\Component;
use yii2tech\config\Manager;

class SomeComponent extends Component
{
    // fields to be configured:
    public $isEnabled = true;
    public $color = '#101010';

    // config manager ;
    private $_configManager;


    public function getConfigManager()
    {
        if ($this->_configManager === null) {
            $this->_configManager = new Manager([
                'source' => $this,
                'storage' => [
                    'class' => 'yii2tech\config\StorageDb',
                    'table' => 'SomeComponentConfig',
                ],
                'items' => [
                    'isEnabled' => [
                        'path' => 'isEnabled',
                        'rules' => [
                            ['boolean']
                        ],
                    ],
                    'color' => [
                        'path' => 'color',
                        'rules' => [
                            ['required']
                        ],
                    ],
                    // ...
                ],
            ]);
        }
        return $this->_configManager;
    }

    public function init()
    {
        parent::init();
        $this->getConfigManager()->configure($this); // populate component with config from DB
    }

    // ...
}

在上面的示例中,字段isEnabledcolor将始终从持久存储中配置。