back

Knowlegde

Knowledge Centre

Creating Custom Services in Drupal 8: A Comprehensive Guide

by editor | 20.11.2018

Creating Custom Services in Drupal 8: A Comprehensive Guide

Dependency injection is a fundamental design pattern in Drupal 8 that promotes code reusability and maintainability. By decoupling functionality, we can write more efficient code that's easier to test and maintain. Let's explore how to implement custom services using dependency injection.

Core Services in Drupal 8

Drupal's core services are defined in the `core.services.yml` file. Here's an example of how a core service is declared:

services:
 path.current:
   class: Drupal\Core\Path\CurrentPathStack
   arguments: ['@request_stack']

This declaration includes three key elements:
- The service name (`path.current`)
- The implementing class
- Required dependencies (passed as arguments)

To use this service in a static context:

// Note: Static service calls should be avoided when possible
$currentPath = \Drupal::service('path.current');
$path = $currentPath->getPath();

Creating a Custom Service

Let's create a custom service in a module called "mymodule". First, create a file named `mymodule.services.yml` in your module's root directory:

services:
 mymodule.tools:
   class: Drupal\mymodule\MyTools
   arguments: ['@database']

Now, let's implement the service class (`MyTools.php`) in the `src` directory:

namespace Drupal\mymodule;
use Drupal\Core\Database\Connection;
/**
* Provides utility functions for working with nodes.
*/
class MyTools {
 /**
  * The database connection.
  *
  * @var \Drupal\Core\Database\Connection
  */
 protected $database;
 /**
  * Constructs a new MyTools service.
  *
  * @param \Drupal\Core\Database\Connection $connection
  *   The database connection.
  */
 public function __construct(Connection $connection) {
   $this->database = $connection;
 }
 /**
  * Retrieves the author ID of a node.
  *
  * @param int $nid
  *   The node ID.
  *
  * @return int|null
  *   The user ID of the node author, or null if not found.
  */
 public function showAuthor($nid) {
   $query = $this->database->select('node_field_data', 'nfd')
     ->fields('nfd', ['uid'])
     ->condition('nfd.nid', $nid);
   
   $result = $query->execute()->fetchAll();
   
   return !empty($result) ? $result[0]->uid : NULL;
 }
}

Accessing Custom Services

There are two main ways to access services:

1. Static Service Container (Not Recommended)

// Avoid this approach in object-oriented code
$toolService = \Drupal::service('mymodule.tools');
$authorId = $toolService->showAuthor(15);

 2. Dependency Injection (Recommended)

/**
* Demonstrates proper service injection.
*/
class MyController extends ControllerBase {
 /**
  * The custom tools service.
  *
  * @var \Drupal\mymodule\MyTools
  */
 protected $myTools;
 /**
  * Constructs a new MyController.
  *
  * @param \Drupal\mymodule\MyTools $my_tools
  *   The custom tools service.
  */
 public function __construct(MyTools $my_tools) {
   $this->myTools = $my_tools;
 }
 /**
  * {@inheritdoc}
  */
 public static function create(ContainerInterface $container) {
   return new static(
     $container->get('mymodule.tools')
   );
 }
 /**
  * Example method using the service.
  */
 public function exampleMethod($nid) {
   $authorId = $this->myTools->showAuthor($nid);
   // Process $authorId as needed
 }
}

Best Practices

1. Always use dependency injection in classes rather than static service calls
2. Name services consistently, starting with your module name
3. Document your service classes and methods thoroughly
4. Include proper type hints and return type declarations
5. Handle error cases and return appropriate default values

By following these patterns, you'll create more maintainable and testable code that integrates well with Drupal's service container architecture.

drupal 8
Top
default
  • Knowlegde
    Knowledge Centre
    Fine-tuning LLaMA to Recreate Eminescu's Literary Style
    editor
  • Knowlegde
    Knowledge Centre
    A New Era Begins: Drupal CMS 1.0 Launches
    editor
  • Knowlegde
    Knowledge Centre
    Bringing AI to B2B
    editor

Post a Comment.