基本上,只要你尝试从模型访问属性,该__get
magic method被调用,它是类似如下:
public function __get($key)
{
return $this->getAttribute($key);
}
正如你所看到的是,__get
魔术方法调用中定义的另一个用户方法(getAttribute
),它是类似如下:
public function getAttribute($key)
{
if (! $key) {
return;
}
// If the attribute exists in the attribute array or has a "get" mutator we will
// get the attribute's value. Otherwise, we will proceed as if the developers
// are asking for a relationship's value. This covers both types of values.
if (array_key_exists($key, $this->attributes) ||
$this->hasGetMutator($key)) {
return $this->getAttributeValue($key);
}
// Here we will determine if the model base class itself contains this given key
// since we do not want to treat any of those methods are relationships since
// they are all intended as helper methods and none of these are relations.
if (method_exists(self::class, $key)) {
return;
}
return $this->getRelationValue($key);
}
在这种情况下(关系),最后一行return $this->getRelationValue($key);
负责检索一段关系。继续阅读源代码,跟踪每个函数调用,你就会明白。从Illuminate\Database\Eloquent\Model.php::__get
开始的方法。顺便说一下,这个代码取自Laravel
的最新版本,但最终过程是相同的。
简短摘要:Laravel在首先检查属性/ $kay
被访问是一个模型的属性或如果它在模型本身则只是简单地返回该属性否则它保持进一步的检查,并且如果所定义的存取方法它在模型中使用该名称创建了一个方法(property/$kay
),然后它只是返回关系。
非常广泛,但总之,它是通过'Model_php'的__get()'访问器来解析的。检查源代码。 –
是的。 Laravel的源代码是开源的。你可以自己看看这个:https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Model.php#L1260 –
它的魔力(功能)。 – apokryfos