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


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

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

这可以以某种方式完成并添加到Yii::$app->params吗?

例如,您可以创建一个类并将详细信息作为数组或对象实例返回?

好的,我找到了怎么做。

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

设置实现接口的类的路径:

app/config/web.php:

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

所以我在位置放置了一个名为 Settings.php 的类: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']访问我的设置。

有关引导内容的其他方法的额外信息,请点击此处。

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

$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'];

另一种方法是在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 中做过这种方法,但现在我更喜欢引导方法