Laravel/Eloquent模型属性可见性

And*_*ton 6 php visibility accessor laravel eloquent

以前我使用的ORM已经将数据库列直接映射到类属性,这允许您具有特定的属性可见性,就像您通常会限制对某些属性(例如密码)的访问一样.

有了Eloquent,我似乎无法复制这个,因为数据库列被映射到不包含可见性的内部属性数组.

我的愿望是将访问用户密码的范围仅限于对象即私有.

设置具有可见性的类属性不起作用,因为此属性超出了Eloquent模型属性的范围,因此该属性未映射到列.

Eloquent $ hidden和$ guarded属性不起作用,因为它们处理大量输出(toArray,toJSON)和质量赋值而不是直接赋值.

我试图使用accessors/mutators(getters/setters)来实现这一目标,结果不一致.

指定访问器上的可见性不起作用,因为调用的访问器方法(例如getPasswordAttribute)是从Eloquent\Model-> getAttribute方法调用的,因此public/protected将始终有效,并且private将始终失败,无论它访问的属性在何处从.

然而,有效的是停止Eloquent访问器完全返回属性,因此对$ user-> password或$ user-> getAttribute('password')的任何请求都会失败,然后有一个单独的方法,其中定义了可见性以便返回直接来自Eloquent属性数组的属性仅在允许的范围内

/**
 * Return password string only for private scope
 * @return string
 */

private function getPassword ()
{
    return $this->attributes['password'];
}

/**
 * Don't return password with accessor
 * @param string $password Password
 * @return void
 * @throws Exception
 */

public function getPasswordAttribute ($password)
{
    throw new Exception ('Password access denied');
}
Run Code Online (Sandbox Code Playgroud)

对于任何想要setter方法可见性的人来说,这种方法也适用于mutators(setter).

这看起来是否正确或是否有更好的"Laravel-Approved"处理方式?:)

ben*_*enJ 3

我不知道这样做的“批准”方式,但你总是可以覆盖 Eloquent 的__get()魔术方法来检查私有字段?

支票debug_backtrace()有点hacky;如果没有,我实际上无法让它按预期工作,因为该getPassword()方法(或基本上该类调用中的任何方法$this->password)仍在使用__get. 这只是检查类调用__get是类本身,而不是另一个类。

它不应该太低效,因为 in_array 检查在执行回溯之前对于非私有属性会失败。不过,可能有更好的方法!

private $private = array(
    'password'
);

public function __get($key)
{
    // check that the class calling __get is this class, and the key isn't 'private'
    if (in_array($key, $this->private) && debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['class'] != get_class()) {
        throw new \Exception('Private');
    }

    // anything else can return as normal
    return parent::__get($key);
}

public function getPassword()
{
    // calling this method elsewhere should work
    return $this->password;
}
Run Code Online (Sandbox Code Playgroud)