How to create a custom service in Drupal


    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


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');

Leave a Comment

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

Scroll to Top