优化Model类代码

This commit is contained in:
thinkphp
2016-05-30 16:01:40 +08:00
parent 031de8c99d
commit 7d72c6743f

View File

@@ -1034,7 +1034,27 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
$value = $this->$method($value, $this->data); $value = $this->$method($value, $this->data);
} elseif (isset($this->type[$name])) { } elseif (isset($this->type[$name])) {
// 类型转换 // 类型转换
$type = $this->type[$name]; $value = $this->writeTransform($value, $this->type[$name]);
}
}
// 标记字段更改
if (!isset($this->data[$name]) || ($this->data[$name] != $value && !in_array($name, $this->change))) {
$this->change[] = $name;
}
// 设置数据对象属性
$this->data[$name] = $value;
}
/**
* 数据写入 类型转换
* @access public
* @param mixed $value 值
* @param string $type 要转换的类型
* @return mixed
*/
protected function writeTransform($value, $type)
{
if (strpos($type, ':')) { if (strpos($type, ':')) {
list($type, $param) = explode(':', $type, 2); list($type, $param) = explode(':', $type, 2);
} }
@@ -1073,15 +1093,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
} }
break; break;
} }
} return $value;
}
// 标记字段更改
if (!isset($this->data[$name]) || ($this->data[$name] != $value && !in_array($name, $this->change))) {
$this->change[] = $name;
}
// 设置数据对象属性
$this->data[$name] = $value;
} }
/** /**
@@ -1100,7 +1112,25 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
return $this->$method($value, $this->data); return $this->$method($value, $this->data);
} elseif (!is_null($value) && isset($this->type[$name])) { } elseif (!is_null($value) && isset($this->type[$name])) {
// 类型转换 // 类型转换
$type = $this->type[$name]; $value = $this->readTransform($value, $this->type[$name]);
} elseif (is_null($value) && method_exists($this, $name)) {
// 获取关联数据
$value = $this->relation()->getRelation($name);
// 保存关联对象值
$this->data[$name] = $value;
}
return $value;
}
/**
* 数据读取 类型转换
* @access public
* @param mixed $value 值
* @param string $type 要转换的类型
* @return mixed
*/
protected function readTransform($value, $type)
{
if (strpos($type, ':')) { if (strpos($type, ':')) {
list($type, $param) = explode(':', $type, 2); list($type, $param) = explode(':', $type, 2);
} }
@@ -1134,12 +1164,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
$value = json_decode($value); $value = json_decode($value);
break; break;
} }
} elseif (is_null($value) && method_exists($this, $name)) {
// 获取关联数据
$value = $this->relation()->getRelation($name);
// 保存关联对象值
$this->data[$name] = $value;
}
return $value; return $value;
} }