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

我想防止模型属性直接从外部源设置,而不通过控制逻辑的设置器。


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;

// or

echo $person->getMoney();

// whatever

如何强制更新此属性的唯一方法是通过规定一些附加逻辑的特定方法?从某种意义上说,将模型属性设置为私有或受保护。


我想单独执行此操作和/或在将模型数据保存到数据库之前执行此操作。


慕仙森
浏览 128回答 2
2回答

交互式爱情

您可以为要保护的每个成员变量重写 set..Attribute() 函数,或者您可以在 set..Attribute() 函数内执行验证,而不是使用单独的公共方法。class Person extends Model{&nbsp; &nbsp; public function addMoney($amount)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ($amount <= 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Exception('Invalid amount');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!isset($this->attributes['money'])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->attributes['money'] = $amount;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->attributes['money'] += $amount;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public function useMoney($amount)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ($amount > $this->money) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Exception('Invalid funds');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!isset($this->attributes['money'])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->attributes['money'] = -$amount;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->attributes['money'] -= $amount;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public function setMoneyAttribute($val) {&nbsp; &nbsp; &nbsp; &nbsp; throw new \Exception('Do not access ->money directly, See addMoney()');&nbsp; &nbsp; }}

幕布斯7119047

使用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 ,它将引发异常。希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP