Yii2 提供可以用属性的方式去获取类的一个方法

时间:2021-08-22 13:21:06

刚开始用 Yii 的小朋友可能对下面的写法非常疑惑:

public function actionIndex()
{
$user = User::find()->where(['name'=>'zhangsan'])->one();
$user->orders; // 关联查询订单表
}

去 User 的 Model 去找 orders 属性也没找到,这个是什么实现的?为什么可以这样写?

其实这个只是 PHP 魔术方法的__get的一种实现。

为了更高的访问了我们的数据,Yii2 提供了可以用属性的方式去获取类的一个方法,Demo如下:

// User Model

public function getOrders()
{
return $this->hasMany(Order::className(), ['user_id' => 'id']);
} // User Controller public function actionView($id)
{
$user = User::find()->where(['name'=>'zhangsan'])->one();
$user->orders; // 此处访问的就是 getOrders() 方法
}

追溯到源代码(yii2\base\Component.php):

/**
* Returns the value of a component property.
* This method will check in the following order and act accordingly:
*
* - a property defined by a getter: return the getter result
* - a property of a behavior: return the behavior property value
*
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when executing `$value = $component->property;`.
* @param string $name the property name
* @return mixed the property value or the value of a behavior's property
* @throws UnknownPropertyException if the property is not defined
* @throws InvalidCallException if the property is write-only.
* @see __set()
*/
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
} else {
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
}