如何设置多个布尔变换器

时间:2015-03-16 16:35:47

标签: laravel laravel-4

我正在使用Laravel 4,我有一个带有很多布尔属性的模型。

对于他们每个人,我都设置了这样的二传手

public function setIsRemoteAttribute($value){
    $this->attributes['isRemote'] = !!$value;
}

和像这样的吸气剂

public function getIsRemoteAttribute($value){
    return !! $this->attributes['isRemote'];
}

有没有办法抽象出来,所以我不是单独设置12个以上的变异器?

2 个答案:

答案 0 :(得分:1)

我猜您可以覆盖setAttribute方法,如:

public function setAttribute($key, $value){
    if(in_array($key, 'abstract_keys')){
        $this->attributes[$key] = !!$value;
    }
    else{
        parent::setAttribute($key, $value);
    }
}

同样适用于getAttribute

答案 1 :(得分:1)

我安装了L5,但我很确定这也适用于L4.2。

如果你查看Eloquent的Model类的代码,你会发现以下方法:

/**
* Set a given attribute on the model.
*
* @param  string  $key
* @param  mixed   $value
* @return void
*/
public function setAttribute($key, $value)
{
    // First we will check for the presence of a mutator for the set operation
    // which simply lets the developers tweak the attribute as it is set on
    // the model, such as "json_encoding" an listing of data for storage.
    if ($this->hasSetMutator($key))
    {
        $method = 'set'.studly_case($key).'Attribute';

        return $this->{$method}($value);
    }

    // If an attribute is listed as a "date", we'll convert it from a DateTime
    // instance into a form proper for storage on the database tables using
    // the connection grammar's date format. We will auto set the values.
    elseif (in_array($key, $this->getDates()) && $value)
    {
        $value = $this->fromDateTime($value);
    }

    if ($this->isJsonCastable($key))
    {
        $value = json_encode($value);
    }

    $this->attributes[$key] = $value;
}

您可以在自己的模型中覆盖此功能:

  • 存储应获取布尔变异符的属性列表
  • 检查$key是否在此元素列表中
  • 如果是 - 做点什么
  • 如果不是,则默认为父实现(此方法)

示例:

public function setAttribute($key, $value)
{
    if (in_array($key, $this->booleans))
    {
        // Do your stuff here - make sure to return it
    }

    return parent::setAttribute($key, $value);
}

您可以对getAttribute方法执行相同的操作。

使用这种方法,您只需将属性的名称添加到布尔值列表中即可使用。

protected $booleans = array('attr1', 'attr2');