Laravel 4.2 用于加密数据的自定义特征

Laravel 4.2 custom trait to encrypt data

我尝试创建自定义特征来自动加密模型的列 'email':

<?php
trait EncryptData
{

public function getAttribute($key)
{
    $value = parent::getAttribute($key);

    if (in_array($key, $this->encryptable)) {
        $value = Crypt::decrypt($value);
    }
    return $value;
}

public function setAttribute($key, $value)
{
    if (in_array($key, $this->encryptable)) {
        $value = Crypt::encrypt($value);
    }

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

我这样启动我的控制器,这会导致异常 Undefined 属性: MyModel::$encryptable:

class MyModel extends BaseController{

Use EncryptData;
protected $encryptable = ['email'];

对此有什么想法吗?

据我了解,这个特征是用来加密模型字段的?

在这种情况下,我应该做的是创建一个 Model class,其中每个模型都从 class.

扩展并添加函数
<?php

class Model {
    protected $encryptable;

    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (in_array($key, $this->encryptable)) {
            $value = Crypt::decrypt($value);
        }
        return $value;
    }
}

-

<?php

class User extends Model {
    function __construct(){
        $this->$encryptable = ['email'];
    }

}

here 是一个很好的特性包。

  • 验证模型特征
  • 清除模型特征
  • 散列模型特征
  • 加密模型特征
  • 杂耍模特特质
  • 软删除模型特征
  • 关联模型特征
  • Sluggable 模型特征

您要找的是CryptingModelTrait。我不能比文档说的更好地描述它。来自文档的简短说明:

此包包含 EncryptingModelTrait,它在使用它的任何 Eloquent 模型上实现 EncryptingModelInterface。 EncryptingModelTrait 向 Eloquent 模型添加方法,以便在设置属性时自动加密模型上的属性,并在获取模型时自动解密模型上的属性。该特征包括以下能力:

设置时自动加密 $encryptable 属性 中的属性 获取属性时自动解密 $encryptable 属性 中的属性 使用 encrypt() and decrypt() 方法手动 encrypt/decrypt 一个值 检查值是否使用 isEncrypted() 方法加密 换出使用 setEncrypter() 方法使用的加密器 class 与所有特性一样,它是独立的,可以单独使用。但是请注意,使用此特征确实会重载模型的魔术 __get()__set() 方法(有关如何处理重载冲突,请参阅 Esensi\Model\Model 源代码)。