logo

Palette - 让它色彩缤纷🎨

Palette — 可视化页面构建器,无需专业设计背景。

在线演示 下载 Palette

滚动

12.15.5. 依赖注入在自定义类/服务中

29/09/2025, by Ivan

Menu

在之前的文章中,我们已经讨论了什么是 Services、Dependency Injection (DI),以及如何在控制器、区块和表单中使用它们:

12.15. Services 和 Dependency Injection
12.15.1. 控制器中的 Dependency Injection
12.15.2. 区块中的 Dependency Injection
12.15.3. BaseForm 中的 Dependencies Injection
12.15.4. ConfigFormBase 配置表单中的 Dependencies Injection

在本文中,我们将演示如何通过 DI 向自定义类/服务中添加服务。让我们以 Book 模块为例进行说明:

/core/modules/book/book.services.yml:

services:
  book.manager:
    class: Drupal\book\BookManager
    arguments: ['@entity.manager', '@string_translation', '@config.factory', '@book.outline_storage', '@renderer']

arguments 中我们指定想要从 Service container 获取的对象,因此无需在类中添加 create() 方法。

/core/modules/book/src/BookManager.php:

<?php

namespace Drupal\book;

use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
...

/**
 * 定义一个 Book 管理器.
 */
class BookManager implements BookManagerInterface {

  /**
   * 实体管理器服务对象.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * 配置工厂服务对象.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * 图书数组.
   *
   * @var array
   */
  protected $books;

  /**
   * 图书大纲存储.
   *
   * @var \Drupal\book\BookOutlineStorageInterface
   */
  protected $bookOutlineStorage;

  /**
   * 存储扁平化的图书树.
   *
   * @var array
   */
  protected $bookTreeFlattened;

  /**
   * 渲染器.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * 构造 BookManager 对象.
   */
  public function __construct(EntityManagerInterface $entity_manager, TranslationInterface $translation, ConfigFactoryInterface $config_factory, BookOutlineStorageInterface $book_outline_storage, RendererInterface $renderer) {
    $this->entityManager = $entity_manager;
    $this->stringTranslation = $translation;
    $this->configFactory = $config_factory;
    $this->bookOutlineStorage = $book_outline_storage;
    $this->renderer = $renderer;
  }

  ...

}

我已删除与 DI 无关的代码,以便更清晰地看到需要在自定义类中添加的部分。在其他方面,添加服务的方式与在控制器中完全相同。