用途:Drupal State API 用于存放应在请求之间持久化、但不属于配置的运行时数据。用户可管理的设置应使用 Config,State 适合内部运营数据,例如上次 cron 运行时间、迁移状态等。
主要能力:通过 StateInterface 注入后调用 get、set、delete,以及 getMultiple、setMultiple、deleteMultiple 批量操作。支持在 get 时提供默认值。State 数据不可导出,不属于配置;与 Cache(临时、变更即失效)和 UserData(按用户偏好)用途不同。
使用方式:注入 StateInterface,例如构造函数参数 private readonly StateInterface $state;读取 $this->state->get('my_module.last_run'),写入 $this->state->set('my_module.last_run', \Drupal::time()->getRequestTime()),删除 delete。批量方法接受键数组或键值数组。服务 ID 为 state。Drush 命令:drush state:get my_module.last_run、drush state:set my_module.feature_enabled 1、drush state:del my_module.last_run。
命名规范:使用带命名空间的键,格式 module_name.key_name,例如 my_module.last_import_time、my_module.processed_count,避免无命名空间的 last_import。
适用场景:记录 cron 上次运行时间、内部功能开关、迁移进度偏移量,以及存储外部 API token 的过期时间等。资料提示敏感密钥不应存于 State,应使用 KeyModule。
限制:资料未提供版本要求、权限要求、性能或并发方面的说明,相关内容暂未提供。