学习yii2.0框架阅读代码(十二)

先把Object、Component、Module三个核心搞清楚了在写实例

下面介绍一下Object -- Yii最基础的类,大多数类都继承了该类。常用的12个公共方法,有点类似于ThinkPHP里面的魔术方法。

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

use Yii;

/**
 * Object is the base class that implements the *property* feature.
 * Object 是一个基础类,实现了属性的功能
 *
 * A property is defined by a getter method (e.g. `getLabel`), and/or a setter method (e.g. `setLabel`). For example,
 * the following getter and setter methods define a property named `label`:
 * 一个定义了 getter 方法和/或者 setter 方法的属性
 *
 * ~~~
 * private $_label;
 *
 * public function getLabel()
 * {
 *     return $this->_label;
 * }
 *
 * public function setLabel($value)
 * {
 *     $this->_label = $value;
 * }
 * ~~~
 *
 * Property names are *case-insensitive*.
 * 属性名是大小写敏感的
 *
 * A property can be accessed like a member variable of an object. Reading or writing a property will cause the invocation
 * of the corresponding getter or setter method. For example,
 * 属性能够被当做对象的成员变量使用
 *
 * ~~~
 * // equivalent to $label = $object->getLabel();
 * $label = $object->label;
 * // equivalent to $object->setLabel(‘abc‘);
 * $object->label = ‘abc‘;
 * ~~~
 *
 * 如果一个属性只有一个getter方法,没有setter方法,它被认为是“只读”。在这种情况下,尝试
 * 修改属性值会导致一个异常.
 *
 * One can call [[hasProperty()]], [[canGetProperty()]] and/or [[canSetProperty()]] to check the existence of a property.
 *
 * Besides the property feature, Object also introduces an important object initialization life cycle. In particular,
 * creating an new instance of Object or its derived class will involve the following life cycles sequentially:
 *
 * 1. 调用构造函数;
 * 2. 根据给定的对象属性初始化配置;
 * 3. init()调用的方法.
 *
 * In the above, both Step 2 and 3 occur at the end of the class constructor. It is recommended that
 * you perform object initialization in the `init()` method because at that stage, the object configuration
 * is already applied.
 *
 * In order to ensure the above life cycles, if a child class of Object needs to override the constructor,
 * it should be done like the following:
 *
 * ~~~
 * public function __construct($param1, $param2, ..., $config = [])
 * {
 *     ...
 *     parent::__construct($config);
 * }
 * ~~~
 *
 * That is, a `$config` parameter (defaults to `[]`) should be declared as the last parameter
 * of the constructor, and the parent implementation should be called at the end of the constructor.
 *
 * Yii最基础的类,大多数类都继承了该类
 *
 * @author Qiang Xue <[email protected]>
 * @since 2.0
 */
class Object implements Configurable
{
    /**
     * Returns the fully qualified name of this class.
     * 获取静态方法调用的类名。返回类的名称,如果不是在类中调用则返回 FALSE。
     *
     * @return string the fully qualified name of this class.
     */
    public static function className()
    {
        // get_called_class -- 后期静态绑定("Late Static Binding")类的名称
        // 就是用那个类调用的这个方法,就返回那个类,返回值中带有 namespace
        return get_called_class();
    }

    /**
     * Constructor.
     * 默认实现做两件事::
     *
     * - 用给定的配置初始化对象的配置.
     * - Call [[init()]].
     *
     * If this method is overridden in a child class, it is recommended that
     *
     * - the last parameter of the constructor is a configuration array, like `$config` here.
     * - call the parent implementation at the end of the constructor.
     *
     * @param array $config name-value pairs that will be used to initialize the object properties
     */
    public function __construct($config = [])
    {
        // 根据 $config 内容初始化该对象
        if (!empty($config)) {
            Yii::configure($this, $config);
        }
        // 调用 init() 方法,继承该类的类可以重写 init 方法,用于初始化
        $this->init();
    }

    /**
     * Initializes the object.
     * 初始化对象
     * This method is invoked at the end of the constructor after the object is initialized with the
     * given configuration.
     */
    public function init()
    {
    }

    /**
     * 返回一个对象属性的值.
     * 不要直接调用这个方法,因为它是一个PHP魔术方法
     * will be implicitly called when executing `$value = $object->property;`.
     *
     * 魔术方法,实现 getter
     *
     * @param string $name the property name
     * @return mixed the property value
     * @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)) {
            // 对象存在 $getter 方法,就直接调用
            return $this->$getter();
        } elseif (method_exists($this, ‘set‘ . $name)) {
            // 如果存在 ‘set‘ . $name 方法,就认为该属性是只写的
            throw new InvalidCallException(‘Getting write-only property: ‘ . get_class($this) . ‘::‘ . $name);
        } else {
            // 否则认为该属性不存在
            throw new UnknownPropertyException(‘Getting unknown property: ‘ . get_class($this) . ‘::‘ . $name);
        }
    }

    /**
     * 设置对象的属性值.
     *
     * 不要直接调用这个方法,因为它是一个PHP魔术方法
     * will be implicitly called when executing `$object->property = $value;`.
     *
     * 魔术方法,实现 setter
     *
     * @param string $name the property name or the event name
     * @param mixed $value the property value
     * @throws UnknownPropertyException if the property is not defined
     * @throws InvalidCallException if the property is read-only
     * @see __get()
     */
    public function __set($name, $value)
    {
        $setter = ‘set‘ . $name;
        if (method_exists($this, $setter)) {
            // 对象存在 $setter 方法,就直接调用
            $this->$setter($value);
        } elseif (method_exists($this, ‘get‘ . $name)) {
            // 如果存在 ‘get‘ . $name 方法,就认为该属性是只读的
            throw new InvalidCallException(‘Setting read-only property: ‘ . get_class($this) . ‘::‘ . $name);
        } else {
            // 否则认为该属性不存在
            throw new UnknownPropertyException(‘Setting unknown property: ‘ . get_class($this) . ‘::‘ . $name);
        }
    }

    /**
     * Checks if the named property is set (not null).
     * 检查指定的属性设置(非空)。
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `isset($object->property)`.
     *
     * 注意,如果没有定义的属性,将返回false.
     *
     * 魔术方法,实现 isset,基于 getter 实现,有 getter 方法的属性才算存在
     *
     * @param string $name the property name or the event name
     * @return boolean whether the named property is set (not null).
     */
    public function __isset($name)
    {
        $getter = ‘get‘ . $name;
        if (method_exists($this, $getter)) {
            // 有 $getter 方法且获取的值不为 null,才认为该属性存在
            return $this->$getter() !== null;
        } else {
            return false;
        }
    }

    /**
     * 对象属性设置为null.
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `unset($object->property)`.
     *
     * Note that if the property is not defined, this method will do nothing.
     * If the property is read-only, it will throw an exception.
     *
     * 魔术方法,实现 unset,基于 setter 实现,有 setter 方法的属性才能 unset 掉
     *
     * @param string $name the property name
     * @throws InvalidCallException if the property is read only.
     */
    public function __unset($name)
    {
        $setter = ‘set‘ . $name;
        if (method_exists($this, $setter)) {
            // 通过 $setter 方法,将它设置为 null
            $this->$setter(null);
        } elseif (method_exists($this, ‘get‘ . $name)) {
            // 如果存在 ‘get‘ . $name 方法,就认为该属性是只读的
            throw new InvalidCallException(‘Unsetting read-only property: ‘ . get_class($this) . ‘::‘ . $name);
        }
    }

    /**
     * 调用指定的方法而不是一个类方法.
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when an unknown method is being invoked.
     * @param string $name the method name
     * @param array $params method parameters
     * @throws UnknownMethodException when calling unknown method
     * @return mixed the method return value
     */
    public function __call($name, $params)
    {
        throw new UnknownMethodException(‘Calling unknown method: ‘ . get_class($this) . "::$name()");
    }

    /**
     * 返回一个值指示是否定义属性.
     * A property is defined if:
     *
     * - the class has a getter or setter method associated with the specified name
     *   (in this case, property name is case-insensitive);
     * - the class has a member variable with the specified name (when `$checkVars` is true);
     *
     * 检查对象或类是否具有 $name 属性,如果 $checkVars 为 true,则不局限于是否有 getter/setter
     *
     * @param string $name the property name
     * @param boolean $checkVars whether to treat member variables as properties
     * @return boolean whether the property is defined
     * @see canGetProperty()
     * @see canSetProperty()
     */
    public function hasProperty($name, $checkVars = true)
    {
        return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
    }

    /**
     * 返回一个值指示是否可以读取属性.
     * A property is readable if:
     *
     * - the class has a getter method associated with the specified name
     *   (in this case, property name is case-insensitive);
     * - the class has a member variable with the specified name (when `$checkVars` is true);
     *
     * 检查对象或类是否能够获取 $name 属性,如果 $checkVars 为 true,则不局限于是否有 getter
     *
     * @param string $name the property name
     * @param boolean $checkVars whether to treat member variables as properties
     * @return boolean whether the property can be read
     * @see canSetProperty()
     */
    public function canGetProperty($name, $checkVars = true)
    {
        // property_exists — 检查对象或类是否具有该属性
        return method_exists($this, ‘get‘ . $name) || $checkVars && property_exists($this, $name);
    }

    /**
     * Returns a value indicating whether a property can be set.
     * A property is writable if:
     *
     * - the class has a setter method associated with the specified name
     *   (in this case, property name is case-insensitive);
     * - the class has a member variable with the specified name (when `$checkVars` is true);
     *
     * 检查对象或类是否能够设置 $name 属性,如果 $checkVars 为 true,则不局限于是否有 setter
     *
     * @param string $name the property name
     * @param boolean $checkVars whether to treat member variables as properties
     * @return boolean whether the property can be written
     * @see canGetProperty()
     */
    public function canSetProperty($name, $checkVars = true)
    {
        return method_exists($this, ‘set‘ . $name) || $checkVars && property_exists($this, $name);
    }

    /**
     * 返回一个值指示是否定义了一个方法.
     *
     * The default implementation is a call to php function `method_exists()`.
     * You may override this method when you implemented the php magic method `__call()`.
     *
     * 检查对象或类是否具有 $name 方法
     *
     * @param string $name the method name
     * @return boolean 是否定义的方法
     */
    public function hasMethod($name)
    {
        return method_exists($this, $name);
    }
}
时间: 2024-08-05 09:00:07

学习yii2.0框架阅读代码(十二)的相关文章

学习yii2.0框架阅读代码(十五)

行为是 yii\base\Behavior 或其子类的实例.行为,也称为mixins,可以无须改变类继承关系即可增强一个已有的 yii\base\Component 类功能.当行为附加到组件后,它将“注入”它的方法和属性到组件,然后可以像访问组件内定义的方法和属性一样访问它们.此外,行为通过组件能响应被触发的事件,从而自定义或调整组件正常执行的代码. <?php namespace yii\base; /** * 行为是所有行为类的基类. * * 一个行为可以用来增强现有的功能组件,无需修改其代

学习yii2.0框架阅读代码(十九)

vendor/yiisoft/yii2/base/Module. php(续) /** * 检索指定的子模块ID. * 这种方法支持检索两个子模块和子模块. * @param string $id module ID (case-sensitive). To retrieve grand child modules, * use ID path relative to this module (e.g. `admin/content`). * @param boolean $load wheth

学习yii2.0框架阅读代码(十八)

vendor/yiisoft/yii2/base/Module. php /** * 返回一个ID,惟一标识此模块在所有模块在当前应用程序. * @return string the unique ID of the module. */ public function getUniqueId() { //如果该模块是一个应用程序,将返回一个空字符串. return $this->module ? ltrim($this->module->getUniqueId() . '/' . $t

学习yii2.0框架阅读代码(十)

vendor/yiisoft/yii2/base/Module. <?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\base; use Yii; use yii\di\ServiceLocator; /** * 模块和应用程序类

学习yii2.0框架阅读代码(十六)

yii\base\InlineAction 追踪一个命令行请求的过程 namespace yii\base; use Yii; /** * InlineAction表示一个动作被定义为一个控制器的方法. * * The name of the controller method is available via [[actionMethod]] which * is set by the [[controller]] who creates this action. * * @author Qi

学习yii2.0框架阅读代码(十四)

组件(Component) 事件Event(温习) <?php namespace yii\base; //事件是所有事件类的基类.它封装了参数与事件相关联. //如果一个事件处理程序集[[进行]]是真的,其余的,uninvoked处理程序将不再被称为处理事件. //另外,添加一个事件处理程序时,额外的数据可能被传递和可以通过[[数据]]属性调用事件处理程序时. class Event extends Object { /** * @var string the event name. This

学习yii2.0框架阅读代码(二十)

vendor/yiisoft/yii2/base/Module. php(续) /** * 新建一个控制器实例基于给定的路线. * * 路线应该是相对于这个模块.该方法实现了以下算法 * to resolve the given route: * * 1. If the route is empty, use [[defaultRoute]]; * 2. If the first segment of the route is a valid module ID as declared in [

学习yii2.0框架阅读代码(二十一)

vendor/yiisoft/yii2/base/Module.php(完) /** * 创建一个控制器基于给定控制器ID. * * The controller ID is relative to this module. The controller class * should be namespaced under [[controllerNamespace]]. * * Note that this method does not check [[modules]] or [[cont

学习yii2.0框架阅读代码(二)

阅读入口文件 <?php //是否运行在调试模式下,如果已经定义了Yii_DEBUG, 则or后面的语句将不会执行 defined('YII_DEBUG') or define('YII_DEBUG', true); //部署当前环境,dev prod 是安装后默认的两个环境,分别表示开发环境和最终的成品环境.此外还有一个 test 环境,表示测试环境. defined('YII_ENV') or define('YII_ENV', 'dev'); // 注册 Composer 自动加载器 re