
Hyperf 模型中的访问器(Accessor)用于在读取模型属性时自动处理、格式化数据,比如拼接字段、转大小写、格式化时间等。它不是靠 PHP 的 magic method __get 直接触发,而是由 Hyperf 数据库模型基类 Hyperf\Database\Model\Model 在 __get() 中统一拦截,并按命名规则查找并调用对应方法。
访问器的命名与定义方式
必须严格遵循 get{AttributeName}Attribute 格式,其中 AttributeName 是「驼峰命名」的字段名(首字母大写),且不带下划线。Hyperf 会自动将数据库字段如 user_name 映射为 userName,再匹配 getUserNameAttribute。
- 数据库字段是
full_name→ 访问器方法名应为getFullNameAttribute - 字段是
created_at→ 方法名为getCreatedAtAttribute(注意不是getCreatedAtAttribute写成getCreated_AtAttribute) - 方法参数
$value是从数据库取出的原始值(可能为 null)
访问器中如何安全使用原始值
数据库字段名错误或字段为空时,Hyperf 默认静默返回 null,不会报错。因此访问器内需主动判空,避免后续类型错误或逻辑中断。
- 用
is_null($value)或isset($value)判断原始值是否有效 - 对字符串操作前加
!empty($value),防止ucfirst(null)返回空字符串却掩盖问题 - 若需默认值,直接在访问器中返回,例如:
return $value ?? '未知用户';
常见实用场景示例
以下写法均放在模型类(如 App\Model\User)内部:
-
拼接姓名:
public function getFullNameAttribute($value) { return "{$this->attributes['first_name']} {$this->attributes['last_name']}"; } -
格式化手机号:
public function getPhoneAttribute($value) { return $value ? substr_replace($value, '****', 3, 4) : ''; } -
日期转中文显示:
public function getCreatedAtAttribute($value) { return $value ? date('Y年m月d日', strtotime($value)) : ''; }
注意事项与避坑点
访问器只影响「读取」,不影响数据库存储;它不会改变 $model->toArray() 或 $model->jsonSerialize() 的默认行为,除非你重写了这些方法。
- 不要在访问器里调用
$this->save()或触发其他写操作,会造成不可预知的循环 - 避免在访问器中做耗时操作(如远程请求、复杂计算),否则每次获取属性都会执行
- 若字段本身是 JSON 类型,Hyperf 会自动解码,访问器收到的是数组/对象,无需再
json_decode - 访问器方法必须是
public,且不能有类型声明(如string返回类型),否则可能被忽略










