chemezov / config
为 Yii2 应用程序运行时配置提供支持
Requires
- yiisoft/yii2: ~2.0.0
README
使用原始的 yii2tech/config。此仓库创建用于修复我们糟糕的 CRM bug。
Yii 2 应用运行时配置扩展
此扩展为应用程序运行时配置提供支持,从数据库加载配置。
有关许可信息,请参阅 LICENSE 文件。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令:
php composer.phar require --prefer-dist yii2tech/config
或添加
"yii2tech/config": "*"
到您的 composer.json 文件的 require 部分。
用法
此扩展允许使用来自外部存储(如关系数据库、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' 属性,路径 'name' 指向 [[\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 界面
此扩展最常见的用途是创建一个网络界面,允许在运行时控制应用程序配置。[[\yii2tech\config\Manager]]不仅用于应用配置,还帮助创建配置编辑的界面。
配置管理的网络控制器可能如下所示
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?']); ?> <?= 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 } // ... }
在上面的示例中,字段isEnabled
和color
将始终从持久存储中配置。