n How to create a Drupal 8 custom service | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Question
How to create a service on drupal 8 ?
How to inject  core services in my custom services in drupal 8 ?

Solution:

Create a Service on Drupal 8

1.  Create a custom module (here : mymodule)

name: 'My Module'
description: 'Custom Module'
package: Custom
type: module
core: 8.x

 

2.  Create service file and add the class as service
Example : mymodule.services.yml

I need to inject a current_user service to get data about current user.

services:
  mymodule.custom_services:
    class: Drupal\mymodule\CustomService
    arguments: ['@current_user']

Arguments contains the names of the services that need to be injected inside our custom service.  '@current_user' is in our case.

3. Create the service Class
Example: src/CustomService.php

<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\AccountInterface;

/**
 * Class CustomService
 * @package Drupal\mymodule\Services
 */
class CustomService {

  protected $currentUser;

  /**
   * CustomService constructor.
   * @param AccountInterface $currentUser
   */
  public function __construct(AccountInterface $currentUser) {
    $this->currentUser = $currentUser;
  }


  /**
   * @return \Drupal\Component\Render\MarkupInterface|string
   */
  public function getData() {
    return $this->currentUser->getDisplayName();
  }

}

 

4. Now you can call your service from other modules.

Example how to call service in hook__preprocess_node(): 

<?php

/**
 *  run cron
 */
function mymodule_preprocess_node(&$variables){

  $data = \Drupal::service('mymodule.custom_services')->getData();
  var_dump($data);
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook