2016-04-26 31 views
0

私は決して変更されない配列をいくつか持っています。Laravelに参照配列を格納

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サービスを呼び出して、私はそれがかなりの接続が増加し、それが良いパスではないかもしれないと思う...

ができこの状況?

答えて

0

あなたは同じ辞書クラス(およびそれのためのインタフェース)を作成し、このように、このデータにそれを保持することができます:

// 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; 
    } 
} 

だけconcretの辞書の定義を追加します。

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();

関連する問題