mcpField
D
drupal-services

drupal-services

github.com/edutrul开发7351 次安装21 周前更新
代码仓库

关于 drupal-services

面向 Drupal 开发者的服务与依赖注入参考,涵盖类、控制器、表单和插件的实现。重点介绍构造函数注入,并提供服务定义、常用服务 ID 和 Drush 生成方式。

主要功能

  1. 01构造函数依赖注入模式
  2. 02控制器和表单示例
  3. 03插件注入示例
  4. 04`services.yml` 定义
  5. 05常用 Drupal 服务 ID
  6. 06使用 Drush 生成服务

适用场景

  1. 01替换类中的静态服务访问
  2. 02为控制器和表单配置服务
  3. 03向插件注入依赖项
  4. 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.managerEntityTypeManagerInterface
current_userAccountProxyInterface
logger.factoryLoggerChannelFactoryInterface
databaseConnection
config.factoryConfigFactoryInterface
rendererRendererInterface
messengerMessengerInterface
date.formatterDateFormatterInterface
language_managerLanguageManagerInterface
path_alias.managerAliasManagerInterface
module_handlerModuleHandlerInterface
cache.defaultCacheBackendInterface

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