How to create a custom service in Drupal

Create mymodule.services.yml

services:
  mymodule.custom_services:
    class: Drupal\mymodule\Services\CustomService
    arguments: []

Now create Services folder under your mymodule/src. After that create CustomService.php in Service folder.

In CustomService.php

<?php

namespace Drupal\mymodule\Services;

/**
 * Class CustomService.
 */
class CustomService {

  /**
   * Constructs a new CustomService object.
   */
  public function __construct() {

  }

  public function getServiceData() {
    //Do something here to get any data.
  }
  /**
   * Here you can pass your values as $array.
   */
  public function postServiceData($array) {
    //Do something here to post any data.
  }
}

And for accessing service in your module file

$service = \Drupal::service('mymodule.custom_services');
$service->getServiceData(); 

https://drupal.stackexchange.com/questions/249634/how-can-i-create-a-custom-service

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top