添加Setter和Getters到Laravel模型 [英] Adding Setters and Getters to Laravel Model
本文介绍了添加Setter和Getters到Laravel模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想要一个有说服力的Model类来为实现一个接口设置setter和getter,那么下面的方法是有意义的,还是有一个'laravel'的方法来解决问题。
If I want an Eloquent Model class to have setters and getters for the sake of implementing an interface does the following approach make sense or is there a 'laravel' approach to the problem
class MyClass extends Model implements someContract
{
public function setFoo($value) {
return parent::__set('foo', $value);
}
public function getFoo() {
return parent::__get('foo');
}
}
推荐答案
你可能正在寻找访问者(getter)和 mutators (setters)。
You are probably looking for accessors (getters) and mutators (setters).
Laravel中的访问者(getter)的示例:
Example of an accessor (getter) in Laravel:
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
Laravel中的mutator(setter)示例:
Example of a mutator (setter) in Laravel:
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
这篇关于添加Setter和Getters到Laravel模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文