drupal-services について
クラス、コントローラー、フォーム、プラグインを実装する Drupal 開発者向けのサービスと依存性注入の資料です。コンストラクター注入を重視し、サービス定義、一般的なサービス ID、Drush による生成方法を紹介します。
主な機能
- 01コンストラクター依存性注入のパターン
- 02コントローラーとフォームの例
- 03プラグイン注入の例
- 04`services.yml` の定義
- 05一般的な Drupal サービス ID
- 06Drush によるサービス生成
活用シーン
- 01クラス内の静的なサービス取得の置き換え
- 02コントローラーやフォームへのサービス設定
- 03プラグインへの依存関係注入
- 04Drush によるサービスのひな形生成
インストール
コマンドをコピーしてターミナルで実行します。
$
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 対応