Drupal 7 global variables vs. Drupal 8 services

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

  }
 

Comments

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

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
9 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.