zoukankan      html  css  js  c++  java
  • Yii2 提供可以用属性的方式去获取类的一个方法

    刚开始用 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() 方法
    }

    追溯到源代码(yii2aseComponent.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);
        }
    }
  • 相关阅读:
    JAVA日期与时间
    CSS的重点知识
    java使用深度优先遍历算法的算法题
    使用python命令行参数的例子
    JAVA中的BigInteger与BigDecimal类功能强大
    软件工程第一次作业
    ORACLE数据库知识点整理
    看懂PL/SQL执行计划
    Oracle Hints详解
    oracle创建用户、授权及角色管理
  • 原文地址:https://www.cnblogs.com/yhdsir/p/5181675.html
Copyright © 2011-2022 走看看