Yii 2は、属性でクラスを取得できる方法を提供します.

3643 ワード

Yiiを使い始めたばかりの子供は、次の書き方に疑問を抱いているかもしれません.
public function actionIndex()
{
    $user = User::find()->where(['name'=>'zhangsan'])->one();
    $user->orders; //        
}

UserのModelに行ってorders属性を探しても見つからなかったのですが、これは何が実現したのですか?どうしてこのように書くことができますか?
実はこれはPHPマジックの方法の_getの実装.
私たちのデータにより高いアクセスを得るために、Yii 2は属性でクラスを取得する方法を提供しています.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()   
}

ソースコード(yii 2baseComponent.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);
    }
}