关于 drupal-services
面向 Drupal 开发者的服务与依赖注入参考,涵盖类、控制器、表单和插件的实现。重点介绍构造函数注入,并提供服务定义、常用服务 ID 和 Drush 生成方式。
主要功能
- 01构造函数依赖注入模式
- 02控制器和表单示例
- 03插件注入示例
- 04`services.yml` 定义
- 05常用 Drupal 服务 ID
- 06使用 Drush 生成服务
适用场景
- 01替换类中的静态服务访问
- 02为控制器和表单配置服务
- 03向插件注入依赖项
- 04使用 Drush 生成服务框架
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-services安装后在 Claude Code 中输入/drupal-services确认已加载。
附带文件README.md
详细介绍
Drupal 服务与依赖注入
核心原则
类中绝不使用 \Drupal::service() — 应通过构造函数注入。
依赖注入模式
控制器与表单(ContainerInjectionInterface)
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class MyController implements ContainerInjectionInterface {
public function __construct(
private readonly AccountProxyInterface $currentUser,
private readonly EntityTypeManagerInterface $entityTypeManager,
) {}
public static function create(ContainerInterface $container): static {
return new static(
$container->get('current_user'),
$container->get('entity_type.manager'),
);
}
}
插件(ContainerFactoryPluginInterface)
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
final class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {
public function __construct(
array $configuration,
string $plugin_id,
mixed $plugin_definition,
private readonly EntityTypeManagerInterface $entityTypeManager,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
);
}
}
服务定义(services.yml)
services:
my_module.my_service:
class: Drupal\my_module\Service\MyService
arguments:
- '@entity_type.manager'
- '@current_user'
- '@logger.factory'
# With autowiring (Drupal 10.3+)
Drupal\my_module\Hook\MyModuleHooks:
autowire: true
常见服务 ID
| 服务 ID | 接口 |
|---|---|
entity_type.manager | EntityTypeManagerInterface |
current_user | AccountProxyInterface |
logger.factory | LoggerChannelFactoryInterface |
database | Connection |
config.factory | ConfigFactoryInterface |
renderer | RendererInterface |
messenger | MessengerInterface |
date.formatter | DateFormatterInterface |
language_manager | LanguageManagerInterface |
path_alias.manager | AliasManagerInterface |
module_handler | ModuleHandlerInterface |
cache.default | CacheBackendInterface |
StringTranslationTrait
对于需要使用 $this->t()、但无需通过完整依赖注入注入翻译服务的类,请添加 use StringTranslationTrait;。
使用 Drush 生成服务
drush generate service --answers='{
"module": "my_module",
"service_name": "my_module.helper",
"class": "HelperService",
"services": ["entity_type.manager", "logger.factory"]
}'
评论
支持 Markdown