如何在 Yii 2 中全局使用自定义设置数据? [英] How to make custom settings data available globally in Yii 2?

查看:18
本文介绍了如何在 Yii 2 中全局使用自定义设置数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

比如你可以创建一个类并以数组或对象实例的形式返回细节?

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

推荐答案

好的,我知道怎么做了.

Ok, I found out how to do it.

基本上你必须实现 bootstrapInterface,一个例子以下是我的情况.

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

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

Set the path to your class that implements the interface:

app/config/web.php:

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

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

So I have placed a class called Settings.php at the location: appaseSettings.php.

然后这是我的 Settings.php 文件:

Then this is my Settings.php file:

namespace appase;

use Yii;
use yiiaseBootstrapInterface;

/*
/* 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'] 全局访问我的设置.

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

关于引导东西的其他方式的额外信息这里.

Extra information on other ways to bootstrap stuff here.

这篇关于如何在 Yii 2 中全局使用自定义设置数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆