Several Drupal 7 global values like global $language and global $user are also now accessed via services in Drupal 8 (and not global variables).
Drupal::languageManager()->getCurrentLanguage() and Drupal::currentUser()
Example:
$lang = \Drupal::languageManager()->getCurrentLanguage(); ksm($lang->getName()); $user = \Drupal::currentUser(); ksm($user->id());
Two ways to get the currentUser data:
1) Procedural code
$user = \Drupal::currentUser(); ksm($user->id());
or
2) OO code access the @current_user service, via dependency injection (DI)
$service = \Drupal::service('thirstysix.ex'); ksm($service->DisplayUserId());
For Example Code:
modules/custom/thirstysix/thirstysix.info.yml
name: Thirsty Six Custom Module description: Custom Module type: module core: 8.x
modules/custom/thirstysix/thirstysix.services.yml
services: thirstysix.ex: class: Drupal\thirstysix\Customservice arguments: ['@current_user']
modules/custom/thirstysix/src/Customservice.php
<?php namespace Drupal\thirstysix; use Drupal\Core\Session\AccountProxy; /** * Drupal 8 service. */ class Customservice { private $currentUser; /** * DependencyInjection. */ public function __construct(AccountProxy $currentUser) { $this->currentUser = $currentUser; } /** * Returns a current Drupal user id. */ public function DisplayUserId() { return $this->currentUser->id(); } }
- Add new comment
- 969 views
Comments
Drupal Global Services, How to use global services in Drupal 8
Submitted by TS (not verified) on Sun, 08/23/2020 - 15:42
The global Drupal class provides static methods to access several of the most common services. As an example, Drupal::cache() returns the cache handler service or in another example Drupal::urlGenerator() returns the URL Generator service. If there is no dedicated method for the service you want to use, you can use the Drupal::service() method to retrieve any defined service.
drush devel-container-services
drush dcs
Add new comment