Configure Drush for Drupal 8 to work from project root

Submitted by Jürgen Haas on Mon, 01/02/2017 - 13:56

8 projects are in most cases controlled by 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
  - /




  
    
  

  - /files
  - /settings
  - /vendor
  - /web
    - /core
    - /libraries
    - /modules
    - /profiles
    - /sites
    - /themes
    - index.php
  - .gitignore
  - composer.json
  - composer.lock

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 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.

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.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.