将Setter和getters添加到Laravel模型

Gaz*_*zer 5 php laravel eloquent

如果我想要一个Eloquent Model类为了实现一个接口而拥有setter和getter,那么下面的方法是否有意义,或者是否有一个"laravel"方法来解决问题

class MyClass extends Model implements someContract
{

  public function setFoo($value) {
      parent::__set('foo', $value);
      return $this;
  }

  public function getFoo() {
      return parent::__get('foo');
  }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*nin 13

您可能正在寻找访问器(getter)和mutators(setter).

Laravel中存取器(getter)的示例:

public function getFirstNameAttribute($value)
{
    return ucfirst($value);
}
Run Code Online (Sandbox Code Playgroud)

Laravel中mutator(setter)的示例:

public function setFirstNameAttribute($value)
{
    $this->attributes['first_name'] = strtolower($value);
}
Run Code Online (Sandbox Code Playgroud)

  • 当通过魔术方法设置属性时,这种方法命名约定似乎更合适,例如“$myClass->first_name = 'BOB';”被设置为“bob”并返回为“Bob”,而不是当我们“实现”合约时。 (2认同)

Abd*_*yir 9

对于新的 Laravel,你可以在 model 中执行此操作:

/**
* Interact with the user's first name.
*
* @param  string  $value
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function firstName(): Attribute
{
    return Attribute::make(
       get: fn ($value) => ucfirst($value),
       set: fn ($value) => strtolower($value),
    );
}
Run Code Online (Sandbox Code Playgroud)

想了解更多吗?参见:(相同的实现)