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

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon