为了账号安全,请及时绑定邮箱和手机立即绑定

如何使 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 关注
  • 124 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信