Blog IT

Dependency Injection is a design pattern that helps decouple the different components of a software application. It is a software design pattern that helps to manage the dependencies between different components in a software system. It involves passing the required dependencies into a class, rather than letting the class create or locate them itself.

This pattern makes writing reusable, testable, and maintainable code easier. Decoupling the components of a system makes it easy to change or update any one component without affecting the others. In this blog, I will outline the process of creating and utilizing a custom service in Drupal 8+ through dependency injection.

Step 1 - Establish a Custom Module within the Appropriate Directory

The first step is to create a custom module within the designated directory. This module should include an info.yml file that outlines the name and relevant details of the custom module.

Step 2 - Implement a Custom Service for Retrieving Node List Based on  User ID

To proceed, we will add a module_services.yml file, as illustrated in the image below. Within this file, we will specify the service class and its dependencies, such as the database argument in this case, as it involves querying the database to obtain the node list.

services:
  custom_service.get_data_user_node:
    class: Drupal\custom_service\GetDataServices
    arguments: ['@database']

Next, we will place the service file within the designated directory, as follows:

/modules/custom/custom_service/src/GetDataServices.php

This is the location of the custom service file, which in this case is named GetDataServices.php and resides within the src folder of the custom module.

<?php
/**
 * @file providing the service that gives the node Id from Node table'.
 *
*/
namespace  Drupal\custom_service;
use Drupal\Core\Database\Connection;
use Drupal\node\Entity\Node;

class GetDataServices {

  private $Database;

	public function __construct(Connection $connection) {
	 $this->database = $connection;
	}
  
  /**
    * Returns list of nids from node table according to passed user id.
  */
  public function drupalise ($uid) {
  	$query = $this->database->select('node_field_data', 'nfd');
  	$query->fields('nfd', ['nid','title','type']);
  	$query->condition('nfd.uid',$uid,'=');
  	$result = $query->execute()->fetchAll();
    // return the result
    return $result;
  }
}

Step 3 - Integrate the Controller and Router within the Custom Module

This step involves adding the necessary code to the controller, which allows us to utilize the service from within the controller. The following code demonstrates this implementation.

The central aspect of this implementation is the utilization of the $container object, which offers a single method, "Get", as follows:

$container->get('');

To commence, we will declare a variable, referred to as $nodedata.

<?php
namespace Drupal\custom_service\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Database\Database;
use Drupal\node\Entity\Node;


/**
 * An example controller.
 */
class GetDataServicesController extends ControllerBase {
  /**
   * The node data.
   *
   * @var \Drupal\custom_service\GetDataServices
  */
  protected $nodedata;

  /**
   * ExampleController constructor.
   *
   * @param \Drupal\custom_service\GetDataServices $node_data
   *   The form builder.
  */
  public function __construct(FormBuilder $form_builder, $node_data) {
    $this->nodeData  = $node_data;
  }

  /**
   * {@inheritdoc}
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The Drupal service container.
   *
   * @return static
   */

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('custom_service.get_data_user_node')
    );
  }
  /**
   * Callback for modal form.
   */
  public function dynamusers($id){
   // Custom service injected like this --
    $all_node = $this->nodeData->drupalise($id);
    $header = [
      'uid' => t('Uid'),
      'title' => t('title'),
      'type' => t('Type'),
    ];
    $rows = [];
    if(!empty($all_node)){
      foreach ($all_node as $key => $value) {
        $rows[] = [$value->nid, $value->title,$value->type];
      }
    }else{
      $rows[] = ['No Record Found'];
    }
    return [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
    ];   
  }
}