如何使自定义设置数据在 Yii 2 中全局可用?

How to make custom settings data available globally in Yii 2?

我正在创建一个将一些设置存储在数据库中的应用程序,理想情况下最好在引导过程中加载这些设置并通过对象全局提供它们。

能否以某种方式完成并添加到 Yii::$app->params

比如你可以创建一个class和return的细节作为数组或对象实例?

好的,我知道怎么做了。

基本上你必须实施bootstrapInterface,下面是我的情况的一个例子。

设置实现接口的 class 路径:

app/config/web.php:

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => [
                    'log',
                    'app\base\Settings',
    ],
    //.............
];

所以我在以下位置放置了一个名为 Settings.php 的 class:app\base\Settings.php.

那么这是我的 Settings.php 文件:

namespace app\base;

use Yii;
use yii\base\BootstrapInterface;

/*
/* The base class that you use to retrieve the settings from the database
*/

class settings implements BootstrapInterface {

    private $db;

    public function __construct() {
        $this->db = Yii::$app->db;
    }

    /**
    * Bootstrap method to be called during application bootstrap stage.
    * Loads all the settings into the Yii::$app->params array
    * @param Application $app the application currently running
    */

    public function bootstrap($app) {

        // Get settings from database
        $sql = $this->db->createCommand("SELECT setting_name,setting_value FROM settings");
        $settings = $sql->queryAll();

        // Now let's load the settings into the global params array

        foreach ($settings as $key => $val) {
            Yii::$app->params['settings'][$val['setting_name']] = $val['setting_value'];
        }

    }

}

我现在可以通过 Yii:$app->params['settings'] 全局访问我的设置。

关于 bootstrap 内容 here 的其他方式的额外信息。

另一种方法是覆盖 baseController 中的 init() 方法。

class BaseController extends Controller{...    
public function init()
    {    
            if(Yii::$app->cache->get('app_config'))
        {
            $config = Yii::$app->cache->get('app_config');
            foreach ($config as $key => $val)
            {
                Yii::$app->params['settings'][$key] = $val->value;
            }
        }
        else
        {
            $config = Config::find()->all();
            $config = ArrayHelper::regroup_table($config, 'name', true);
            Yii::$app->cache->set('app_config', $config, 600);

            foreach ($config as $key => $val)
            {
                Yii::$app->params['settings'][$key] = $val->value;
            }
        }
}
....}    

这取决于你。我曾经在 Yii1 中使用过这种方法,但现在我更喜欢 bootstrap 方法

我来晚了一点,但有一种更简单的方法可以做到这一点。

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => [
                    'log',
    ],
    //.............
    'params' = [
        'adminEmail' => 'admin@example.com',
        'defaultImage' => '/images/default.jpg',
        'noReplyEmail' => 'noreply@example.com'
    ],
];

现在您可以使用以下语法简单地访问这些变量

$adminEmail = \Yii::$app->params['adminEmail'];