LoginSignup
0
0

More than 1 year has passed since last update.

LaravelでClass定数を使う

Posted at

定数定義をどこで行うのかという話になった際に、クラス定数を作成してそこに定義するという話題があったので実装方法を調べてみた

Class定数の作成方法

App内にConstsディレクトリを作成

 ※ディレクトリ名は、何でも問題ない

app
 └── consts

その中に定数ファイルを作成

NotificationConst.php 
<?php
Namespace App\Consts; 

Class NotificationConst {
    const MAX_DISPLAY = 20; 
    const PUBLIC = '公開'; 
    const PRIVATE = '非公開';
}

エイリアスの設定

app.phpファイル内のaliasesに設定を記述
app
 └── config
        └── app.php
<?php

return [

    'aliases' => [ 

      'App' => Illuminate\Support\Facades\App::class,
      'Arr' => Illuminate\Support\Arr::class,

      /** 省略 */

      /** 追加 */
      'NotificationConst' => App\Consts\NotificationConst::class
      
    ]
]

定義ファイルをエイリアスに設定したらあとは、呼び出したいファイル内で呼ぶ

Controllerの場合 Bladeで使用する
@if($publicStatus === NotificationConst:: PUBLIC) 
    <p>{{ $title }}</p>
    <p>{{ $contents}}</p>
@endif

この方法で、Classを使って定数を定義出来る。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0