We can achieve this by using create a service and for custom service we required to create custom module.
Step 1: Create the custom_module.info.yml
yml Copydescription: 'Custom Module'
package: Custom
type: module
core: 8.x
Step 2: Create the custom_module.services.yml file in your custom module
yml Copycustom_module.custom_services:
class: Drupal\custom_module\CustomService
arguments: ['@current_user']
Arguments contains services name that we injected inside our custom service. i.e. '@current_user' is in our case.
Step:3 Create the service class under src/CustomService.php :
php Copy<?php
namespace Drupal\custom_module;
use Drupal\Core\Session\AccountInterface;
/**
* Class CustomService
* @package Drupal\custom_module\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();
}
}
Step:4 Create the service class under src/CustomService.php :
php Copy<?php
/**
* run cron
*/
function custom_module_preprocess_node(&$variables){
$data = \Drupal::service('custom_module.custom_services')->getData();
var_dump($data);
}