Skip to main content

Accessor

Trait Accessor 

Source
pub trait Accessor {
    // Required methods
    fn data_map(&self) -> &HashMap<String, Value>;
    fn data_map_mut(&mut self) -> &mut HashMap<String, Value>;
    fn accessor_cache(&self) -> &HashMap<String, Value>;
    fn accessor_cache_mut(&mut self) -> &mut HashMap<String, Value>;

    // Provided methods
    fn real_field_name(&self, name: &str) -> String { ... }
    fn accessor_for(&self, field: &str, value: Option<&Value>) -> Value { ... }
    fn get_attr(&mut self, name: &str) -> Value { ... }
    fn get_data(&self, name: &str) -> Option<&Value> { ... }
    fn has_attr(&mut self, name: &str) -> bool { ... }
}
Expand description

访问器 trait — 对齐 PHP getAttr / getXxxAttr

§PHP 对齐

PHP 方法Rust 等价说明
getAttr($name)Self::get_attr()入口方法,含缓存
getData($name)Self::get_data()取原始字段值(不触发访问器)
getXxxAttr($value, $data)Self::accessor_for()业务模型按字段派发
getRealFieldName($name)Self::real_field_name()字段名归一化
__isset($name)Self::has_attr()触发访问器判 null
$this->dataSelf::data_map()原始字段数组
$this->getSelf::accessor_cache()访问器结果缓存

§缓存机制

  • 首次 get_attr(field) 触发访问器,结果缓存到 accessor_cache
  • 同名字段被 set_attr 时失效对应缓存
  • PHP bug 复刻:不同名字段修改不失效派生字段缓存 (如 set_attr("status", ...) 不失效 status_text 缓存)

Required Methods§

Source

fn data_map(&self) -> &HashMap<String, Value>

取原始字段数组(对应 PHP $this->data

Source

fn data_map_mut(&mut self) -> &mut HashMap<String, Value>

取可变原始字段数组

Source

fn accessor_cache(&self) -> &HashMap<String, Value>

取访问器缓存(对应 PHP $this->get

Source

fn accessor_cache_mut(&mut self) -> &mut HashMap<String, Value>

取可变访问器缓存

Provided Methods§

Source

fn real_field_name(&self, name: &str) -> String

字段名归一化(对应 PHP getRealFieldName

PHP 默认 $strict=true, $convertNameToCamel=false → 原样返回。 业务模型按需重写以支持 snake_case ↔ camelCase 转换。

Source

fn accessor_for(&self, field: &str, value: Option<&Value>) -> Value

业务模型重写:按字段名派发到具体访问器

§参数
  • field:归一化后的字段名
  • value:原始字段值(来自 data_map,可能为 None
§返回

访问器计算后的值(对应 PHP getXxxAttr($value, $this->data) 返回值)

§默认实现

返回原始字段值(或 Value::Null),等价于 PHP 无访问器时走 $type / 关联 / 原值分支。

Source

fn get_attr(&mut self, name: &str) -> Value

入口方法 — 对应 PHP getAttr($name)

执行流程(对齐 Attribute.php 第 497-540 行):

  1. 字段名归一化
  2. 缓存命中 → 直接返回
  3. 取原始字段值
  4. 派发到 accessor_for
  5. 写入缓存
Source

fn get_data(&self, name: &str) -> Option<&Value>

取原始字段值(不触发访问器)— 对应 PHP getData($name)

Source

fn has_attr(&mut self, name: &str) -> bool

检测字段是否存在 — 对应 PHP __isset($name)

PHP 行为复刻isset($model->field) 触发访问器执行并缓存结果。

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§