Drupal 9: How to register a service

By Fernando Katsukawa, 16 November, 2022

This should also work for Drupal 8 and Drupal 10 versions.

In the Drupal, from the 8 version, a service can be registered and used calling the services container.

Services are often used to help Drupal to decouple features and functionalities.

Services are defined in the module's .services.yml file, as the core in core.services.yml

So, to register a custom service in your custom module, all you have to do is, create a file using the pattern below and put it in the root folder of your custom module:

my_module.services.yml

Next, inside it, you can specify the service name, followed by its class and services dependencies.

my_custom_service:
  class: Drupal\my_module\MyServiceClass
  arguments: ['@entity_type.manager']

MyServiceClass.php

<?php

namespace Drupal\my_module;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * My service class.
 */
class MyServiceClass {

  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * My service class construtor.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }
  
  /**
   * Load node by title.
   *
   * @param string $title
   *   The title used to load the node.
   *
   * @return Node|null
   *   Return the found Term object or NULL.
   */
  public function loadNodeByTitle($title):Node|null {
    $nodes = $this->entityTypeManager->getStorage('node')
      ->loadByProperties([
        'title' => $pid,
      ]);

    return ($nodes) ? reset($nodes) : NULL;
  }
}    

Now, you can call your service using the generic \Drupal::service() method or by calling using Dependency Injection.

Using generic \Drupal::service() method

$my_custom_service_instance = \Drupal::service('my_custom_service');

$node = $my_custom_service_instance->loadNodeByTitle($title);

Dependency Injection will be explained in another topic because it have some particularities that needs to be explained better.

About the Author

Profile picture for user fkatsukawa

Fernando Katsukawa is a certified senior backend developer, who have been worked with Drupal in the last 12 years and counting...

Saved your precious time? Use the cup below to buy me a coffee!
buy me a coffee - cup