Creating a custom Drupal service allows you to encapsulate functionality and access it wherever needed, promoting modularity and reusability within your codebase as a Helper.
In this article we are sharing an example of how to create a custom Drupal service and use it as a helper.
Step 1: Define the Service
Create a new custom module or use an existing one. Define your service in the module’s directory
custom_module.services.yml file, below shown the sample.
Step 2: Create the Service Class
Create a new PHP class
CustomServiceHelper.php, that implements the service's functionality
Step 3: Use the Service as a Helper
You can now use your custom service as a helper wherever needed in your Drupal codebase, below is an example used in the confirm form
This is a basic example of creating a custom Drupal service and using it as a helper. You can expand upon this pattern to encapsulate more complex functionality and integrate it into various parts of your Drupal site.