본문 바로가기
카테고리 없음

모델 Model - Const / this & self 활용

by Sein_ 2023. 12. 19.
728x90

 

this  모델 자기자신
self  상수 자신

 

예시 1)

특정 모델의 컬럼 값이 해당 모델의 특정 상수값일 경우 

- 특정 상태의 조건이 변경되면 모든 코드에서 조건을 찾아다 변경을 해줘야되는 불편이 있다.

 

[기존코드]

 

//Tmon Controller

if ($order->status === Tmon::CANCEL)

 

[수정코드]

//Tmon Model

public const CANCEL = '1';

public function isCancel(): bool
{
    return $this->status === self::CANCEL;
}

 

//Tmon Controller

$order->isCancelOrder()

 

 

 

예시 2)

특정 모델에 정의된 상수값을 나열하여 사용하는 경우

- 나열해서 사용해야될 값이 추가될 경우 전부 찾아 추가해주어야한다.

 

[기존코드]

//Grip Model

public const YET = -2;
public const UNAVAILABLE = -1;
public const PREPARING = 0;
public const START = 1;

    public static function statusLabel($status): string
    {
        return match ($status) {
            self::YET => '발송대기',
            self::UNAVAILABLE => '발송불가',
            self::PREPARING => '발송준비중',
            self::START => '발송완료',
            default => '알수없음',
        };
    }

 

//gripList View

<td class="text-center" title="발송">
    <?= Grip::statusLabel($gripOrder->state) ?>
</td>

...

<select name="delivery_state" id="" class="form-control">
<option value="<?=Grip::START?>" <?=$state === (string)Grip::START? "selected" : "" ?>><?=Grip::statusLabel(Grip::START)?></option>
<option value="<?=Grip::PREPARING?>" <?=$state === (string)Grip::PREPARING? "selected" : "" ?>><?=Grip::statusLabel(Grip::PREPARING)?></option>
<option value="<?=Grip::UNAVAILABLE?>" <?=$state === (string)Grip::UNAVAILABLE? "selected" : "" ?>><?=Grip::statusLabel(Grip::UNAVAILABLE)?></option>
<option value="<?=Grip::YET?>" <?=$state === (string)Grip::YET? "selected" : "" ?>><?=Grip::statusLabel(Grip::YET)?></option>
</select>

 

[수정코드]

 
//Grip Model

public const YET = -2;
public const UNAVAILABLE = -1;
public const PREPARING = 0;
public const START = 1;

public const TYPES = [
    self::YET => '발송대기',
    self::UNAVAILABLE =>'발송불가',
    self::PREPARING => '발송준비중',
    self::START => '발송완료',
];

 

//gripList View

<td class="text-center" title="발송">
    <?= Grip::TYPES[$order->state] ?>
</td>

...

<select name="state" id="" class="form-control">
  <option value="">전체</option>
  <?php
     foreach (Grip::TYPES as $typeKey => $typeValue) {
  ?>
  <option value="<?= $typeKey ?>" <?= $state === (string)$typeKey ? "selected" : "" ?>><?= $typeValue ?></option>
  <?php }
  ?>
</select>