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

查看:216
本文介绍了如何在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?

推荐答案

好,我知道了如何做.

基本上,您必须实现 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',
                    'app\base\Settings',
    ],
    //.............
];

因此,我在app\base\Settings.php位置放置了一个名为Settings.php的类.

So I have placed a class called Settings.php at the location: 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']全局访问我的设置.

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

此处.

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

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