Laravel模型中的動(dòng)態(tài)屬性

Laravel的文檔里對(duì)于Model的動(dòng)態(tài)屬性講的比較簡(jiǎn)略,理解起來(lái)有些模糊,最近在偉大的蝦米的帶領(lǐng)下終于搞明白了,在此做一個(gè)比較詳細(xì)的總結(jié)。

一、引入

首先上Laravel文檔相關(guān)部分。一對(duì)一關(guān)聯(lián)是很基本的關(guān)聯(lián)。例如一個(gè)User模型也許會(huì)對(duì)應(yīng)一個(gè)Phone。要定義這種關(guān)聯(lián),我們必須將phone方法放置于User模型上。phone方法應(yīng)該要返回基類Eloquent上的hasOne方法的結(jié)果:

<?phpnamespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{ 
    /** 
    * 獲取與指定用戶互相關(guān)聯(lián)的電話紀(jì)錄。 
    */ 
    public function phone() { 
        return $this->hasOne('App\Phone'); 
    }
}

傳到hasOne方法里的第一個(gè)參數(shù)是關(guān)聯(lián)模型的類名稱。定義好關(guān)聯(lián)之后,我們就可以使用Eloquent的動(dòng)態(tài)屬性來(lái)獲取關(guān)聯(lián)紀(jì)錄。動(dòng)態(tài)屬性讓你能夠訪問(wèn)關(guān)聯(lián)函數(shù),就像他們是在模型中定義的屬性:

$phone = User::find(1)->phone;

但這里只講了動(dòng)態(tài)屬性的最簡(jiǎn)單的一種形式,也就是調(diào)用的屬性不存在,但存在同名的方法時(shí),則會(huì)調(diào)用同名的方法,返回的類型是collection類型(Eloquent的集合)。下文讓我們走一遍Laravel的源代碼看看還有其他幾種不同種類的動(dòng)態(tài)屬性。

二、Laravel源代碼trace

1、對(duì)于動(dòng)態(tài)屬性疑問(wèn)的產(chǎn)生

蝦米在梅林項(xiàng)目的blade里用到了一個(gè)方法,但是usermodel里并不存在同名的avatar_src()方法,但是存在一個(gè)getAvatarSrcAttribute()名字有點(diǎn)像的方法,當(dāng)時(shí)就覺(jué)得很懵逼,看代碼的確是調(diào)用了這個(gè)方法,但不知是如何關(guān)聯(lián)起來(lái)的,所以想搞明白這里面的邏輯究竟是怎么回事。

<a href="#"><img src="{{ Auth::user()->avatar_src }}" alt=""></a>

2、__get()

那么問(wèn)題來(lái)了,如何追溯?這里需要的一個(gè)預(yù)備知識(shí)是關(guān)于PHP的魔術(shù)方法__get(),當(dāng)讀取不可訪問(wèn)屬性的值時(shí),__get()會(huì)被調(diào)用。所以決定從這個(gè)方法開(kāi)始進(jìn)行追溯。具體的方法是在PhpStorm里打開(kāi)user模型的代碼,在菜單欄選擇Navigate-File Structure,彈出的框子里勾選Show inherited members,英文輸入狀態(tài)下輸入get可以找到我們想要的方法,點(diǎn)進(jìn)去可以看到__get()方法源代碼如下:

    /**
     * Dynamically retrieve attributes on the model.
     *
     * @param  string  $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->getAttribute($key);
    }

3、getAttribute($key)

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

        return $this->getRelationValue($key);
    }

第一個(gè)if的左半邊,如果這個(gè)model有這個(gè)attribute那么就直接返回,沒(méi)什么可說(shuō)的。
第一個(gè)if的右半邊mutator是變異體的意思事實(shí)上處理了本節(jié)開(kāi)頭的疑問(wèn),看一下源代碼:

    /**
     * Determine if a get mutator exists for an attribute.
     *
     * @param  string  $key
     * @return bool
     */
    public function hasGetMutator($key)
    {
        return method_exists($this, 'get'.Str::studly($key).'Attribute');
    }

本方法的作用是判斷所調(diào)用的這個(gè)不存在的屬性是否存在“按照一定格式變形的類似名字的方法”。所謂的“一定格式”可以參考Studly caps命名法,對(duì)應(yīng)的源代碼:

    /**
     * Convert a value to studly caps case.
     *
     * @param  string  $value
     * @return string
     */
    public static function studly($value)
    {
        $key = $value;

        if (isset(static::$studlyCache[$key])) {
            return static::$studlyCache[$key];
        }

        $value = ucwords(str_replace(['-', '_'], ' ', $value));

        return static::$studlyCache[$key] = str_replace(' ', '', $value);
    }

注意到經(jīng)studly caps處理過(guò)的-和_都會(huì)被去掉。再回到hasGetMutator($key)這個(gè)方法,我們可以看到Laravel會(huì)嘗試去尋找名字形似getStudlyCapsNameAttribute()的方法,如果有的話則會(huì)在getAttribute($key)里返回相關(guān)的值。第一小節(jié)提到的例子對(duì)應(yīng)的方法名我們可以知道當(dāng)調(diào)用這個(gè)不存在的屬性avatar_src時(shí),Laravel會(huì)嘗試調(diào)用getAvatarSrcAttribute()這個(gè)方法,看了下代碼果然是存在這個(gè)方法的,開(kāi)始的疑問(wèn)解決啦~

4、getRelationValue($key)

回到getAttribute($key)這個(gè)方法,如果在第一個(gè)if里沒(méi)有返回則會(huì)調(diào)用getRelationValue($key)這個(gè)方法,源代碼如下:

    /**
     * Get a relationship.
     *
     * @param  string  $key
     * @return mixed
     */
    public function getRelationValue($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 ($this->relationLoaded($key)) {
            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.
        if (method_exists($this, $key)) {
            return $this->getRelationshipFromMethod($key);
        }
    }

第一個(gè)if注釋寫(xiě)得很清楚了,第二個(gè)if就是判斷是否存在和所調(diào)用屬性同名的方法,如果存在則調(diào)用getRelationshipFromMethod($key)方法。

5、getRelationshipFromMethod($method)

這個(gè)方法比較關(guān)鍵,我們看一下源代碼:

    /**
     * Get a relationship value from a method.
     *
     * @param  string  $method
     * @return mixed
     *
     * @throws \LogicException
     */
    protected function getRelationshipFromMethod($method)
    {
        $relations = $this->$method();

        if (! $relations instanceof Relation) {
            throw new LogicException('Relationship method must return an object of type '
                .'Illuminate\Database\Eloquent\Relations\Relation');
        }

        $this->setRelation($method, $results = $relations->getResults());

        return $results;
    }

注意if語(yǔ)句塊那里的判斷,意味著與屬性同名的方法的返回類型必須是Relation類型或者是它的子類,例如hasMany等。所以如果要另外做處理,返回的類型不為Relation的話可以參考第四小節(jié)那樣的命名法構(gòu)造相關(guān)方法名。另外,setRelation那一行的意思是將沒(méi)有加載的relation進(jìn)行加載,那么下次需要時(shí)就可以在getRelationValue($key)的第一個(gè)if中即返回需要的結(jié)果。還有值得注意的是此方法最后的返回值返回的$resultsCollection類型,也就是說(shuō)如果調(diào)用不存在的動(dòng)態(tài)屬性后返回的是Collection類型,而如果我們直接調(diào)用方法返回的則是Relation類型,可以在其上構(gòu)造查詢進(jìn)一步處理,而再調(diào)用getResults()后才能再獲得Collection類型的返回值。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 國(guó)家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說(shuō)閱讀 12,452評(píng)論 6 13
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,656評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,753評(píng)論 18 399
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,076評(píng)論 0 9
  • 那是遺落在冷清街道的一個(gè)影子 憑身形,依稀辨來(lái)是個(gè)醉漢 旁邊癱坐著幾個(gè)酒瓶,唱得有氣無(wú)力: 生活,已是如此艱難 我...
    青色的木頭閱讀 275評(píng)論 1 2

友情鏈接更多精彩內(nèi)容