How to create a custom service in Drupal

Solved Drupal Errors

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

Tags

What do you think?

Leave a Reply

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

Related articles

Contact us

Partner with Us for Comprehensive IT

We’re happy to answer any questions you may have and help you determine which of our services best fit your needs.

Your benefits:
What happens next?
1

We Schedule a call at your convenience 

2

We do a discovery and consulting meting 

3

We prepare a proposal 

Schedule a Free Consultation