簡體   English   中英

Laravel / Eloquent模型屬性可見性

[英]Laravel / Eloquent Model Attribute Visibility

以前我使用的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');
}

對於任何想要setter方法可見性的人來說,這種方法也適用於mutators(setter)。

這看起來是否正確或是否有更好的“Laravel-Approved”處理方式? :)

我不知道這樣做的“批准”方式,但你總是可以覆蓋__get()__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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM