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