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.
services: | |
custom_service_helper: | |
class: '\Drupal\custom_module\CustomServiceHelper' | |
arguments: ['@logger.factory'] |
Step 2: Create the Service Class
Create a new Php class CustomServiceHelper.php
, that implements the service's functionality
<?php | |
namespace Drupal\custom_module; | |
use Drupal\Core\Logger\LoggerChannelFactory; | |
/** | |
* Helper CustomServiceHelper. | |
*/ | |
class CustomServiceHelper { | |
/** | |
* Messenger service. | |
* | |
* @var Drupal\Core\Logger\LoggerChannelFactory | |
*/ | |
protected $loggerFactory; | |
/** | |
* Constructs a helper. | |
* | |
* @param Drupal\Core\Logger\LoggerChannelFactory $logger_factory | |
* The Logger. | |
*/ | |
public function __construct(LoggerChannelFactory $logger_factory) { | |
$this->loggerFactory = $logger_factory; | |
} | |
/** | |
* Helper function. | |
* | |
* @param array $array1 | |
* Array of data. | |
* @param array $array2 | |
* Array of attached access control groups. | |
* | |
* @return string | |
* A string | |
*/ | |
public function getConcatData($array1, $array2) { | |
try { | |
$data = []; | |
foreach ($array1 as $_array1) { | |
foreach ($array2 as $_array2) { | |
if ($_array1 === $_array2) { | |
$data[] = $_array2; | |
} | |
} | |
} | |
return implode(", ", $data); | |
} | |
catch (\Exception $e) { | |
$this->loggerFactory->get('custom_module')->notice('Error:' . $e); | |
} | |
} | |
} |
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 CustomConfirmForm.php
.
<?php | |
namespace Drupal\custom_module\Form; | |
use Drupal\Core\Form\ConfirmFormBase; | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\Core\Logger\LoggerChannelFactory; | |
use Drupal\Core\TempStore\PrivateTempStoreFactory; | |
use Drupal\custom_module\CustomServiceHelper; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
/** | |
* CustomConfirmForm. | |
*/ | |
class CustomConfirmForm extends ConfirmFormBase { | |
/** | |
* Messenger service. | |
* | |
* @var Drupal\Core\Logger\LoggerChannelFactory | |
*/ | |
protected $loggerFactory; | |
/** | |
* Helper. | |
* | |
* @var \Drupal\custom_module\CustomServiceHelper | |
*/ | |
protected $helper; | |
/** | |
* Construct. | |
* | |
* @param Drupal\Core\Logger\LoggerChannelFactory $logger_factory | |
* The Logger. | |
* @param Drupal\custom_module\CustomServiceHelper $helper | |
* The Helper. | |
*/ | |
public function __construct(LoggerChannelFactory $logger_factory, CustomServiceHelper $helper) { | |
$this->loggerFactory = $logger_factory; | |
$this->helper = $helper; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function create(ContainerInterface $container) { | |
return new static( | |
$container->get('logger.factory'), | |
$container->get('custom_service_helper'), | |
); | |
} | |
/** | |
* Get the form id. | |
*/ | |
public function getFormId(): string { | |
return 'custom_confirm_form'; | |
} | |
/** | |
* Get the confirmation question. | |
*/ | |
public function getQuestion(): TranslatableMarkup { | |
return $this->t('Are you sure?'); | |
} | |
/** | |
* Get Cancel URL. | |
*/ | |
public function getCancelUrl(): Url { | |
return new Url('system.admin_content'); | |
} | |
/** | |
* Build form. | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state): array { | |
$form = parent::buildForm($form, $form_state); | |
$form['custom'] = [ | |
'#type' => 'fieldset', | |
'#title' => $this->t('Confirm?'), | |
]; | |
$data = $this->helper->getConcatData(['hello', 'world'], ['hello', 'its', 'custom service']); | |
$form['custom']['data'] = [ | |
'#type' => 'item', | |
'#title' => 'Data', | |
'#markup' => $data, | |
]; | |
return $form; | |
} | |
/** | |
* Validate the form. | |
*/ | |
public function validateForm(array &$form, FormStateInterface $form_state): void { | |
parent::validateForm($form, $form_state); | |
} | |
/** | |
* Submit the form. | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state): void { | |
$form_state->setRedirect('system.admin_content'); | |
} | |
} |
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.
Thanks for reading the article, for more drupal related articles read and subscribe to peoples blog articles.