Model类增加append属性和append方法 用于toarray和tojson方法输出的时候 附加额外的属性,该属性的值必须通过获取器定义

This commit is contained in:
thinkphp
2016-05-19 11:36:25 +08:00
parent 0fd61503a8
commit 323d3e9416

View File

@@ -48,6 +48,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
protected $field = [];
// 隐藏属性
protected $hidden = [];
// 追加属性
protected $append = [];
// 数据信息
protected $data = [];
// 记录改变字段
@@ -174,6 +176,18 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
return array_key_exists($name, $this->data) ? $this->data[$name] : $this->data;
}
/**
* 设置需要追加的输出属性
* @access public
* @param array $append 属性列表
* @return $this
*/
public function append($append = [])
{
$this->append = $append;
return $this;
}
/**
* 设置需要隐藏的属性
* @access public
@@ -194,6 +208,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
public function toArray()
{
$item = [];
if (!empty($this->append)) {
foreach ($this->append as $name) {
$item[$name] = $this->__get($name);
}
}
foreach ($this->data as $key => $val) {
// 如果是隐藏属性不输出
if (in_array($key, $this->hidden)) {