Skip to main content
January 02, 2017

Configure Drush for Drupal 8 to work from project root

by Jürgen Haas

Drupal 8 projects are in most cases controlled by Composer and following best practices, the directory structure of a Drupal project looks similar to this (more details have already been covered here):

- Project Root
  - /config
  - /console
  - /drush
  - /files
  - /settings
  - /vendor
  - /web
    - /core
    - /libraries
    - /modules
    - /profiles
    - /sites
    - /themes
    - index.php
  - .gitignore
  - composer.json
  - composer.lock

DrupalConsole has already been enhanced such that you can call it from anywhere within that directory tree. However, Drush requires that your current directory is somewhere below the Drupal root, which is the /root/web directory in the example above. Now, that can be a pain. During development you'll find yourself often to go to the project root to call something like composer update and even more often going to the Drupal root to be able to call drush cache-rebuild. Changing the directories all the time is not nice, to say the least. With DrupalConsole that wouldn't be necessary and you could do both, Composer and DrupalConsole, from the project's root directory. But there are reasons why you want to use Drush, either exclusively or as a companion.

Well, there is a nice and easy solution to that. You only have to add the following lines of code to the drushrc.php file in either the /.drush subdirectory of your user home or in the global Drush configuration directory, e.g. /etc/drush on Linux based systems.

Here is the code:

if (file_exists('./web/index.php') && file_exists('./web/core')) {
  $options['r'] = realpath('./web');
}

What's doing this? Well, it tests if your current directory is the project's root by looking for the index.php and the core subdirectory in a web subdirectory. If that's the case, it adds an option r with the real path of the Drupal root, which tells Drush where to bootstrap Drupal from.

It's that simple and it just works. No downsides recognized so far.

Tools

Add new comment

Klartext

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA