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()');
}
}

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 ,它將引發異常。希望這可以幫助。
- 2 回答
- 0 關注
- 179 瀏覽
添加回答
舉報