Laravel
的文檔里對于Model
的動態屬性講的比較簡略,理解起來有些模糊,最近在偉大的蝦米的帶領下終于搞明白了,在此做一個比較詳細的總結。
一、引入
首先上Laravel文檔相關部分。一對一關聯是很基本的關聯。例如一個User
模型也許會對應一個Phone
。要定義這種關聯,我們必須將phone
方法放置于User
模型上。phone
方法應該要返回基類Eloquent
上的hasOne
方法的結果:
<?phpnamespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 獲取與指定用戶互相關聯的電話紀錄。
*/
public function phone() {
return $this->hasOne('App\Phone');
}
}
傳到hasOne
方法里的第一個參數是關聯模型的類名稱。定義好關聯之后,我們就可以使用Eloquent
的動態屬性來獲取關聯紀錄。動態屬性讓你能夠訪問關聯函數,就像他們是在模型中定義的屬性:
$phone = User::find(1)->phone;
但這里只講了動態屬性的最簡單的一種形式,也就是調用的屬性不存在,但存在同名的方法時,則會調用同名的方法,返回的類型是collection
類型(Eloquent
的集合)。下文讓我們走一遍Laravel
的源代碼看看還有其他幾種不同種類的動態屬性。
二、Laravel源代碼trace
1、對于動態屬性疑問的產生
蝦米在梅林項目的blade里用到了一個方法,但是user
的model
里并不存在同名的avatar_src()
方法,但是存在一個getAvatarSrcAttribute()
名字有點像的方法,當時就覺得很懵逼,看代碼的確是調用了這個方法,但不知是如何關聯起來的,所以想搞明白這里面的邏輯究竟是怎么回事。
<a href="#"><img src="{{ Auth::user()->avatar_src }}" alt=""></a>
2、__get()
那么問題來了,如何追溯?這里需要的一個預備知識是關于PHP
的魔術方法__get()
,當讀取不可訪問屬性的值時,__get()
會被調用。所以決定從這個方法開始進行追溯。具體的方法是在PhpStorm
里打開user
模型的代碼,在菜單欄選擇Navigate-File Structure,彈出的框子里勾選Show inherited members,英文輸入狀態下輸入get可以找到我們想要的方法,點進去可以看到__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);
}
第一個if的左半邊,如果這個model有這個attribute那么就直接返回,沒什么可說的。
第一個if的右半邊mutator是變異體的意思事實上處理了本節開頭的疑問,看一下源代碼:
/**
* 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');
}
本方法的作用是判斷所調用的這個不存在的屬性是否存在“按照一定格式變形的類似名字的方法”。所謂的“一定格式”可以參考Studly caps命名法,對應的源代碼:
/**
* 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);
}
注意到經studly caps處理過的-和_都會被去掉。再回到hasGetMutator($key)
這個方法,我們可以看到Laravel會嘗試去尋找名字形似getStudlyCapsNameAttribute()
的方法,如果有的話則會在getAttribute($key)
里返回相關的值。第一小節提到的例子對應的方法名我們可以知道當調用這個不存在的屬性avatar_src
時,Laravel會嘗試調用getAvatarSrcAttribute()
這個方法,看了下代碼果然是存在這個方法的,開始的疑問解決啦~
4、getRelationValue($key)
回到getAttribute($key)
這個方法,如果在第一個if里沒有返回則會調用getRelationValue($key)
這個方法,源代碼如下:
/**
* 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);
}
}
第一個if注釋寫得很清楚了,第二個if就是判斷是否存在和所調用屬性同名的方法,如果存在則調用getRelationshipFromMethod($key)
方法。
5、getRelationshipFromMethod($method)
這個方法比較關鍵,我們看一下源代碼:
/**
* 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語句塊那里的判斷,意味著與屬性同名的方法的返回類型必須是Relation
類型或者是它的子類,例如hasMany
等。所以如果要另外做處理,返回的類型不為Relation
的話可以參考第四小節那樣的命名法構造相關方法名。另外,setRelation
那一行的意思是將沒有加載的relation
進行加載,那么下次需要時就可以在getRelationValue($key)
的第一個if中即返回需要的結果。還有值得注意的是此方法最后的返回值返回的$results
是Collection
類型,也就是說如果調用不存在的動態屬性后返回的是Collection
類型,而如果我們直接調用方法返回的則是Relation
類型,可以在其上構造查詢進一步處理,而再調用getResults()
后才能再獲得Collection
類型的返回值。