Laravel从数据库加载设置 [英] Laravel load settings from database

查看:148
本文介绍了Laravel从数据库加载设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用Laravel 5从数据库加载设置/配置的有效方法.设置由keyvalue列组成,模型类基本上如下所示:

I'm looking for an efficient way to load settings/configuration from the database with Laravel 5. Settings consist of a key and value column, the model class basically looks like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $table = 'settings';
    protected $fillable = ['key', 'value'];
    protected $primaryKey = 'key';
}

首先,我做了一个简单的辅助函数来完成这项工作.问题是,这将导致每个页面请求多个调用.越来越慢了.

At first I made a simple helper function which does the job. The problem is, this would lead to multiple calls per page request. Which is getting slow.

/**
 * Get the value for the given setting from the database.
 *
 * @param  string  $key
 * @return string
 */
function setting($key)
{
    $setting = Setting::whereKey($key)->firstOrFail();

    return $setting->value;
}

// $foo = setting('foo'); returns 'bar'

为了改善这一点,我在App\Classes目录中创建了一个名为Setting的自定义类(并为此创建了一个Facade):

In an attempt to improve this I creating a custom class called Setting within the App\Classes directory (and also created a Facade for it):

<?php

namespace App\Classes;

use Cache;

class Setting {

    /**
     * The array of settings
     *
     * @var array $settings
     */
    protected $settings = [];

    /**
     * Instantiate the class.
     */
    public function __construct()
    {
        $this->loadSettings();
    }

    /**
     * Pull the settings from the database and cache them.
     *
     * @return void;
     */
    protected function loadSettings()
    {
        $settings = Cache::remember('settings', 24*60, function() {
            return \App\Setting::all()->toArray();
        });

        $this->settings = array_pluck($settings, 'value', 'key');
    }

    /**
     * Get all settings.
     *
     * @return array;
     */
    public function all()
    {
        return $this->settings;
    }

    /**
     * Get a setting value by it's key.
     * An array of keys can be given to retrieve multiple key-value pair's.
     *
     * @param  string|array  $key;
     * @return string|array;
     */
    public function get($key)
    {
        if( is_array($key) ) {
            $keys = [];

            foreach($key as $k) {
                $keys[$k] = $this->settings[$k];
            }

            return $keys;
        }

        return $this->settings[$key];
    }

}

// $foo = Setting::get('foo');

现在我的问题是:这是解决此问题的最佳方法吗?我现在在构造类时缓存所有设置.然后从缓存中检索设置值.

And now for my question: is this the best way to tackle this problem? I'm now caching all the settings when the class gets constructed. And then retrieve setting values from the cache after that.

我开始了解L5中的Repository模式,但我还没有.我认为在这种情况下这会太过分了.我很想听听我的方法是否有意义.

I'm beginning to understand the Repository pattern in L5, but I'm not there yet. I thought that would be overkill in this case. I would love to hear if my approach makes any sence.

推荐答案

恕我直言,这有点过分设计了.您可以使用辅助方法进行相同的操作:

IMHO it's a bit over engineered. You can do the same with the helper approach:

function settings($key)
{
    static $settings;

    if(is_null($settings))
    {
        $settings = Cache::remember('settings', 24*60, function() {
            return array_pluck(App\Setting::all()->toArray(), 'value', 'key');
        });
    }

    return (is_array($key)) ? array_only($settings, $key) : $settings[$key];
}

少麻烦.没有循环.每个请求最多命中1个DB.每个请求最多1次命中缓存.

Less cumbersome. No loops. Max 1 DB hit per request. Max 1 Cache hit per request.

这篇关于Laravel从数据库加载设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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