Skip to main content
Submitted by manoj on 17 August 2022
d7

Services are used to perform operations like accessing the database or sending an e-mail and many more.

service name : To define  service  name follow pattern  ‘module_name’ concatenate with a ‘unique_name’ ie. [module_name.unique_name]

Arguments contains the names of the services that need to be injected inside our custom service. Example: '@current_user' 

Drupal 8 service container

We can achieve by using create a service. and for custom service we required to create custom modules

service class file will be kept under the ‘src’ folder.

Create your own Services in Drupal

Step 1: Create the [module_name].info.yml

name: 'Custom Module'
description: 'My Custom Module'
package: Custom
type: module
core: 8.x

Step 2: Create the [module_name].services.yml file in your custom module

services:
  custom_code.custom_service:
    class: Drupal\custom_code\CustomService
    arguments: ['@current_user']

Step:3 Create the src/MysService.php Class :

<?php

namespace Drupal\custom_code;

use Drupal\Core\Session\AccountInterface;

/**
 * Class CustomService
 * @package Drupal\custom_code\Services
 */
class CustomService {

  protected $currentUser;

  /**
   * CustomService constructor.
   * @param AccountInterface $currentUser
   */
  public function __construct(AccountInterface $currentUser) {
    $this->currentUser = $currentUser;
  }


  /**
   * @return \Drupal\Component\Render\MarkupInterface|string
   */
  public function getData() {
    return $this->currentUser->getDisplayName();
  }

}

Call your service

 

$data = \Drupal::service('mymodule.custom_services')->getData();
  var_dump($data);
d9