通用存取器和更改器在Laravel 4 [英] Universal accessors and mutators in Laravel 4

查看:62
本文介绍了通用存取器和更改器在Laravel 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以为各个字段定义访问器和变异器,如下所示:

I know it's possible to define accessors and mutators for individual fields, like so:

public function setSomeAttribute($value) {
    // set the attribute
}
public function getSomeAttribute() {
    // return the attribute}
}

但是是否可以定义一个将用于 all 属性获取和设置的后备方法?

But is it possible to define a fallback method that will be used for all attribute gets and sets?

原因是我想即时将任何空值转换为空值,以保持数据库整洁,并允许可空字段为空而不是空字符串(如果有更好的方法,请告诉我!)

The reason being that I want to convert any empty values to null values on the fly, to keep my database clean and allow nullable fields to be null instead of an empty string (if there's a better way to do this let me know!)

我正在寻找类似的东西

public function setAttribute($property,$value) {
    $this->$property = empty($value) ? null : $value;
}

更新:

感谢Chris Goosey,我找到了一个对我有用的解决方案.我扩展了Eloquent模型方法setAttribute,并将其设置为默认值(如果为空).在我的数据库中通常为null,零或空字符串,因此对我有用!

Thanks to Chris Goosey I've found a solution that works for me. I extended the Eloquent model method setAttribute, and I set the value to the column default if it's empty. That's usually null, zero or an empty string in my databases so works for me!

public function setAttribute($key, $value)
{
    // Convert empty values to their default values (e.g. null, zero)
    if(empty($value) && $this->getSchema()->hasColumn($key)) {
        $value = $this->getSchema()->getColumn($key)->getDefault();
    }
    parent::setAttribute($key,$value);
}

推荐答案

最好的方法可能是扩展Eloquent类,以覆盖setAttribute和getAttribute方法.

Best way is probably to extend the Eloquent class overwriting the setAttribute and getAttribute methods.

要让您的所有模型都继承这些覆盖的方法,您需要创建一个扩展雄辩的类,例如

For all your models to inherit these overwritten methods you would want to create a class that extends eloquent e.g.

<?php 

class BaseModel extends eloquent {

    public function setAttribute($property,$value) {
        $this->$property = empty($value) ? null : $value;
    }

    public function getAttribute($key) {
        // Do Stuff
    }
}

,然后所有模型都应从该新类扩展,例如

and then all your models should extend from this new class, e.g.

<?php

class User extends BaseModel {
    protected $table = 'users';
}

值得一提的是,新方法应该具有旧方法的所有功能以及新功能,这就是getAttribute()的样子(Illuminate \ Database \ Eloquent第2212行):

It is also worth mentioning your new methods should have all the functionality of the old method plus your new functionality, this is what the getAttribute() looks like (Illuminate\Database\Eloquent line 2212):

/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

和同一文件中的setAttribute看起来像这样(第2338行):

and the setAttribute in the same file looks like this (line 2338):

/**
 * 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()))
    {
        if ($value)
        {
            $value = $this->fromDateTime($value);
        }
    }

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

希望这会有所帮助!

这篇关于通用存取器和更改器在Laravel 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆