Skip to content

Commit

Permalink
改进获取器
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Feb 24, 2021
1 parent 123a095 commit 48e01bd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
3 changes: 3 additions & 0 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,9 @@ public function refresh(bool $relation = false)
if ($this->exists) {
$this->data = $this->db()->find($this->getKey())->getData();
$this->origin = $this->data;
$this->get = [];
$this->set = [];
$this->readDataType();

if ($relation) {
$this->relation = [];
Expand Down
20 changes: 16 additions & 4 deletions src/model/concern/Attribute.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ trait Attribute
*/
protected $strict = true;

/**
* 获取器数据
* @var array
*/
private $get = [];

/**
* 修改器执行记录
* @var array
Expand Down Expand Up @@ -266,7 +272,7 @@ public function getOrigin(string $name = null)
}

/**
* 获取对象原始数据 如果不存在指定字段返回false
* 获取当前对象数据 如果不存在指定字段返回false
* @access public
* @param string $name 字段名 留空获取全部
* @return mixed
Expand Down Expand Up @@ -479,8 +485,12 @@ protected function getValue(string $name, $value, $relation = false)
{
// 检测属性获取器
$fieldName = $this->getRealFieldName($name);
$method = 'get' . Str::studly($name) . 'Attr';

if (array_key_exists($fieldName, $this->get)) {
return $this->get[$fieldName];
}

$method = 'get' . Str::studly($name) . 'Attr';
if (isset($this->withAttr[$fieldName])) {
if ($relation) {
$value = $this->getRelationValue($relation);
Expand All @@ -504,6 +514,8 @@ protected function getValue(string $name, $value, $relation = false)
$this->relation[$name] = $value;
}

$this->get[$fieldName] = $value;

return $value;
}

Expand All @@ -516,9 +528,9 @@ protected function readDataType(): void
{
foreach ($this->data as $key => $value) {
if (isset($this->type[$key])) {
$this->data[$key] = $this->readTransform($value, $this->type[$key]);
$this->get[$key] = $this->readTransform($value, $this->type[$key]);
} elseif ($this->autoWriteTimestamp && in_array($key, [$this->createTime, $this->updateTime])) {
$this->data[$key] = $this->getTimestampValue($value);
$this->get[$key] = $this->getTimestampValue($value);
}
}
}
Expand Down

0 comments on commit 48e01bd

Please sign in to comment.