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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27778477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:31:29  来源:igfitidea点击:

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

phpyiiyii2

提问by Brett

I'm creating an application which stores some settings in the database and ideally it would be good to load these settings during bootstrapping and make them available via an object globally.

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

Can this be done and added to Yii::$app->paramssomehow?

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

Such as you can create a class and return the details as an array or object instance?

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

回答by Brett

Ok, I found out how to do it.

好的,我找到了方法。

Basically you have to implement the bootstrapInterface, an example below for my situation.

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

Set the path to your class that implements the interface:

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

app/config/web.php:

应用程序/配置/web.php:

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

So I have placed a class called Settings.phpat the location: app\base\Settings.php.

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

Then this is my Settings.phpfile:

然后这是我的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'];
        }

    }

}

I can now access my settings via Yii:$app->params['settings']globally.

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

Extra information on other ways to bootstrap stuff here.

此处提供有关引导程序的其他方法的额外信息。

回答by SynackSA

I'm a little late to the party, but there is a much easier way to do this.

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

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => [
                    'log',
    ],
    //.............
    'params' = [
        'adminEmail' => '[email protected]',
        'defaultImage' => '/images/default.jpg',
        'noReplyEmail' => '[email protected]'
    ],
];

Now you can simply access those variables with the following syntax

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

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

回答by Stas Panyukov

Another way to do it is override init() method in the baseController.

另一种方法是覆盖 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;
            }
        }
}
....}    

It`s up to you. I used to do this method in Yii1 but now I would prefer bootstrap method

这取决于你。我曾经在 Yii1 中使用此方法,但现在我更喜欢引导程序方法