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 关注
- 149 浏览
添加回答
举报