tp5的获取器和修改器是自动触发的吗?

来源:2-2 表的设计(一)

jip0303

2017-08-26

tp5的获取器和修改器是自动触发的吗?  看手册貌似也没有什么关键字定义他们是获取器或者修改器,函数外跟普通函数没啥区别。

写回答

1回答

singwa

2017-08-26

您好,读取器和修改器的原始方法入口是在thinkphp/library/think/Model.php,然后如果是读取器就是定位到getAttr方法如下:

/**
 * 获取器 获取数据对象的值
 * @access public
 * @param string $name 名称
 * @return mixed
 * @throws InvalidArgumentException
 */
public function getAttr($name)
{
    try {
        $notFound = false;
        $value    = $this->getData($name);
    } catch (InvalidArgumentException $e) {
        $notFound = true;
        $value    = null;
    }

    // 检测属性获取器
    $method = 'get' . Loader::parseName($name, 1) . 'Attr';
    if (method_exists($this, $method)) {
        $value = $this->$method($value, $this->data);
    } elseif (isset($this->type[$name])) {
        // 类型转换
        $value = $this->readTransform($value, $this->type[$name]);
    } elseif (in_array($name, [$this->createTime, $this->updateTime])) {
        if (is_string($this->autoWriteTimestamp) && in_array(strtolower($this->autoWriteTimestamp), [
            'datetime',
            'date',
            'timestamp',
        ])
        ) {
            $value = $this->formatDateTime(strtotime($value), $this->dateFormat);
        } else {
            $value = $this->formatDateTime($value, $this->dateFormat);
        }
    } elseif ($notFound) {
        $relation = Loader::parseName($name, 1, false);
        if (method_exists($this, $relation)) {
            $modelRelation = $this->$relation();
            // 不存在该字段 获取关联数据
            $value = $this->getRelationData($modelRelation);
            // 保存关联对象值
            $this->relation[$name] = $value;
        } else {
            throw new InvalidArgumentException('property not exists:' . $this->class . '->' . $name);
        }
    }
    return $value;
}

看到上面的$method = 'get' . Loader::parseName($name, 1) . 'Attr';  请仔细看这个这个地方 ,  如果你在自己模块下的model中 定义了 getXxxxAttr的话 就会先读取这个方法,比如你在model中定义了getStatusAttr 如下

function getStatusAttr($status) {
    return $status == 1 ? 99 : 0;
}

OK,那如果是这样的话, 我们下次获取表的内容的时候,当表中status=1的时候,我们通过PHP获取的话那返回的status就是99了。


希望我的回答能帮到您,祝您学习愉快,有问题欢迎随时沟通

0
1
jip0303
非常感谢!
2017-08-28
共1条回复

Thinkphp5.0仿百度糯米开发多商家电商平台

【毕设】BAT大牛亲授ThinkPHP 5.0,实战中学透新技能,应用于工作

2439 学习 · 1712 问题

查看课程