Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

If you need to do some file level operations, like scanning some files in Drupal, you should use the app.root container parameter to get the absolute path of the Drupal installation. Previously the install location was stored in the global variable DRUPAL_ROOT.

Before

class Example implements ContainerInjectionInterface {

  public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
  }

  public function create(ContainerInterface $container) {
    return new static($container->get('entity.manager'));
  }
  
  public function example() {
    file_scan_directory(DRUPAL_ROOT);
  }

After

class Example implements ContainerInjectionInterface {

  public function __construct($root, EntityManagerInterface $entity_manager) {
    $this->root = $root;
    $this->entityManager = $entity_manager;
  }

  public function create(ContainerInterface $container) {
    return new static($container->get('app.root'), $container->get('entity.manager'));
  }
  
  public function example() {
    file_scan_directory($this->root);
  }

Using the constant in .module scope

In case you have DRUPAL_ROOTin a .module file,
or you can't inject the 'app.root' you can use


$app_root = \Drupal::root();
Impacts: 
Module developers