亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使 Eloquent 模型屬性只能通過公共方法更新?

如何使 Eloquent 模型屬性只能通過公共方法更新?

PHP
慕仙森 2023-07-01 17:43:03
我想防止模型屬性直接從外部源設置,而不通過控制邏輯的設置器。class Person extends Model{    public function addMoney($amount)    {        if ($amount <= 0) {            throw new Exception('Invalid amount');        }        $this->money += $amount;    }    public function useMoney($amount)    {        if ($amount > $this->money) {            throw new Exception('Invalid funds');        }        $this->money -= $amount;    }}這是不應該允許的:$person->money = -500;您必須使用某種訪問器或設置器方法:$person->useMoney(100);但我不在乎你如何獲得價值:echo $person->money;// orecho $person->getMoney();// whatever如何強制更新此屬性的唯一方法是通過規定一些附加邏輯的特定方法?從某種意義上說,將模型屬性設置為私有或受保護。我想單獨執行此操作和/或在將模型數據保存到數據庫之前執行此操作。
查看完整描述

2 回答

?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

您可以為要保護的每個成員變量重寫 set..Attribute() 函數,或者您可以在 set..Attribute() 函數內執行驗證,而不是使用單獨的公共方法。


class Person extends Model

{

    public function addMoney($amount)

    {

        if ($amount <= 0) {

            throw new Exception('Invalid amount');

        }


        if (!isset($this->attributes['money'])) {

            $this->attributes['money'] = $amount;

        } else {

            $this->attributes['money'] += $amount;

        }

    }


    public function useMoney($amount)

    {

        if ($amount > $this->money) {

            throw new Exception('Invalid funds');

        }


        if (!isset($this->attributes['money'])) {

            $this->attributes['money'] = -$amount;

        } else {

            $this->attributes['money'] -= $amount;

        }

    }


    public function setMoneyAttribute($val) {

        throw new \Exception('Do not access ->money directly, See addMoney()');

    }


}


查看完整回答
反對 回復 2023-07-01
?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

使用mutator,您的代碼應如下所示:

class Person extends Model

{

? ? public function setMoneyAttribute($amount)

? ? {

? ? ? ? if ($amount < 0) {

? ? ? ? ? ? throw new Exception('Invalid amount');

? ? ? ? }

? ? ? ? $this->attributes['money'] = $amount;

? ? ? ? $this->save();

? ? }


? ?public function addMoney($amount)

? ? {

? ? ? ? if ($amount <= 0) {

? ? ? ? ? ? throw new Exception('Invalid amount');

? ? ? ? }

? ? ? ? $this->money += $amount;

? ? }


? ? public function useMoney($amount)

? ? {

? ? ? ? if ($amount > $this->money) {

? ? ? ? ? ? throw new Exception('Invalid funds');

? ? ? ? }

? ? ? ? $this->money -= $amount;

? ? }

}

現在,您可以使用 $person->money = -500 ,它將引發異常。希望這可以幫助。


查看完整回答
反對 回復 2023-07-01
  • 2 回答
  • 0 關注
  • 179 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號