SuperAPI AI 工具集

drupal-services

编程与开发

查看项目

更新于 10-15 21:37

技能介绍

用途:面向 Drupal 模块开发,规范服务(services)与依赖注入(DI)的使用,让控制器、表单和插件以可测试方式获取核心服务。核心原则:不要在类里调用 \Drupal::service(),应通过构造函数注入。

主要能力与用法: 控制器与表单实现 ContainerInjectionInterface,在 __construct 中接收依赖(如 AccountProxyInterface、EntityTypeManagerInterface),并在静态 create(ContainerInterface $container) 中用 $container->get() 获取服务。 插件实现 ContainerFactoryPluginInterface,构造函数在 $configuration、$plugin_id、$plugin_definition 之后追加注入的服务,并调用 parent::__construct();create() 同样通过容器获取。 服务定义写在 services.yml,用 arguments 以 @服务名 引用依赖,例如 @entity_type.manager、@current_user、@logger.factory;Drupal 10.3+ 支持 autowire: true 自动装配。 常用服务 ID 与接口:entity_type.manager、current_user、logger.factory、database、config.factory、renderer、messenger、date.formatter、language_manager、path_alias.manager、module_handler、cache.default。 需要 $this->t() 时可在类中使用 StringTranslationTrait,而无需完整注入翻译服务。 可用 Drush 生成服务:drush generate service --answers='{"module":"my_module","service_name":"my_module.helper","class":"HelperService","services":["entity_type.manager","logger.factory"]}'。

适用场景:Drupal 自定义模块开发、块插件与自定义插件编写、服务注册与依赖管理。限制:资料未提供具体版本兼容范围(除 autowire 标注 Drupal 10.3+ 外)、未提供完整项目配置或收费信息,部分细节暂未提供。