How to user Dependencies injection in a custom class/service in Drupal 8/9
This article provides an example of how to add services via DI in a custom class/service. Let's look at the example of the Book module:
/core/modules/book/book.services.yml:
services:
book.manager:
class: Drupal\book\BookManager
arguments: ['@entity.manager', '@string_translation', '@config.factory', '@book.outline_storage', '@renderer']
In arguments, we specify which objects we want to get from the Service container, so we don't need to add the create() method to our class.
/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;
...
/**
* Defines a book manager.
*/
class BookManager implements BookManagerInterface {
/**
* Entity manager Service Object.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Config Factory Service Object.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Books Array.
*
* @var array
*/
protected $books;
/**
* Book outline storage.
*
* @var \Drupal\book\BookOutlineStorageInterface
*/
protected $bookOutlineStorage;
/**
* Stores flattened book trees.
*
* @var array
*/
protected $bookTreeFlattened;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Constructs a BookManager object.
*/
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;
}
...
}
I've removed the non-DI code from the example to make it easier to see what needs to be added to the custom class. In all other respects, adding services is the same as in the controller.