在 Larawel 中存储引用数组

storing reference arrays in Laravel

本文关键字:引用 数组 存储 Larawel      更新时间:2023-09-26

我有几个永远不会改变的数组。

Gender ( 'M' => trans('core.male'), 
    'F' => trans('core.female'), 
    'X' => trans('core.mixt')

Grades (...the same, with 20 grades that will never change)
AgeCategory (...the same, with 5 categories that will never change)

现在,我不想将其存储在数据库中,因为它永远不会更改,我可以将其存储在本地,以避免无用的查询。

但是我需要同时使用Laravel和Javascript(VueJs)访问它。

我应该怎么做,而不是重复代码。

我可以在服务器中一次性编写所有这些内容,然后调用 Web 服务,但我认为它会显着增加连接,这可能不是好途径......

知道我应该如何处理这种情况吗?

您可以创建相同的字典类(以及它的接口)并像这样保存此数据:

// base dictionary
abstract class BaseDictionary 
{
    protected $data = [];
    protected $translatedList = null;
    public function get($key, $default = null) {
        $value = array_get($this->data, $key, $default);
        if ($value != $default) {
            return trans($value);
        }
        return $value;
    }
    public function getList()
    {
        if (is_null($this->translatedList)) {
            $this->translatedList = [];
            foreach ($this->data as $key => $value) {
                $this->translatedList[$key] = trans($value);
            }
        }
        return $this->translatedList;
    }
}

并仅添加具体字典定义:

class Gender extends BaseDictionary 
{
    protected $data = [
        'M' => 'core.male',
        'F' => 'core.female',
        'X' => 'core.mixt'
    ];
}

您还可以将其作为单一实例绑定到服务提供商中:

'App::singleton(Gender::class)

之后,调用将如下所示:

app(Gender::class)->get('F');

那是为了翻译。对于整个列表:

app(Gender::class)->getList();