关于 drupal-state
drupal-state 是 Drupal State API 的技能参考,讲解运行时操作数据及其与配置、缓存和用户数据的区别,适合需要跨请求保存内部值的 Drupal 开发者。
主要功能
- 01State API 读写示例
- 02带命名空间的键名规范
- 03State、配置与缓存对比
- 04Drush State 命令
适用场景
- 01记录上次 Cron 运行时间
- 02保存迁移进度
- 03管理内部功能开关
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-state安装后在 Claude Code 中输入/drupal-state确认已加载。
附带文件README.md
详细介绍
Drupal State API
State 用于存储需要在多个请求之间持久保存的运行时数据,但不是配置。用户管理的设置请使用 Config。内部操作数据(如上次运行 cron 的时间、迁移状态等)请使用 State。
基本用法
use Drupal\Core\State\StateInterface;
// Inject
public function __construct(
private readonly StateInterface $state,
) {}
// Get
$value = $this->state->get('my_module.last_run');
$value = $this->state->get('my_module.last_run', $default_value);
// Set
$this->state->set('my_module.last_run', \Drupal::time()->getRequestTime());
// Delete
$this->state->delete('my_module.last_run');
// Get multiple
$values = $this->state->getMultiple(['key1', 'key2']);
// Set multiple
$this->state->setMultiple([
'my_module.status' => 'active',
'my_module.count' => 42,
]);
// Delete multiple
$this->state->deleteMultiple(['key1', 'key2']);
命名约定
使用命名空间键:module_name.key_name
// Good
$this->state->get('my_module.last_import_time');
$this->state->get('my_module.processed_count');
// Bad
$this->state->get('last_import'); // Not namespaced
State、Config 与 Cache 的区别
| 存储 | 用途 | 可导出 |
|---|---|---|
| State | 运行时操作数据(上次运行时间、计数器、标志) | 否 |
| Config | 用户管理的设置、站点配置 | 是(通过 cex/cim) |
| Cache | 计算开销大的数据,发生更改时会失效 | 否(临时) |
| UserData | 每位用户的偏好设置/数据 | 否 |
常见用例
// Track last cron run
$this->state->set('my_module.cron_last', \Drupal::time()->getRequestTime());
// Feature flag (internal)
$isEnabled = $this->state->get('my_module.feature_enabled', FALSE);
// Track migration progress
$this->state->set('my_module.migration_offset', $offset);
// Store external API token (not sensitive — use KeyModule for secrets)
$this->state->set('my_module.api_token_expires', $expires);
Drush State 命令
# Get
drush state:get my_module.last_run
# Set
drush state:set my_module.feature_enabled 1
# Delete
drush state:del my_module.last_run
服务 ID
state
评论
支持 Markdown