Xdebug over the command line with DDEV

I moved over to DDEV for my local development stack back in February. One of my favorite things is the ease of using Xdebug. You can configure Xdebug to always be enabled, or turn it on and off as needed (my preferred method.) When you have Xdebug enabled, it also enables it for any PHP scripts executed over the command line. That means you can debug your Drush or Drupal Console scripts like a breeze!

This article is based on using Xdebug within PhpStorm, as it is my primary IDE.

Thumbnail

When using PhpStorm with any non-local stack you will have to set up a mapping. This allows PhpStorm to understand what files on your local stack match the contents within the PhpStorm project. For example, DDEV serves files from /var/www/html within its containers but the project files are actually /Users/myuser/Sites/awesomeproject  on your machine.

If you haven't yet, set up the configuration for this mapping. Generally, I never do this upfront and wait until the first time I end up using Xdebug over a web request and PhpStorm prompts me to. In this configuration, you will provide a server name. I set this as the DDEV domain for my project.

Thumbnail

Now, to get Xdebug over the CLI to work we need to ensure a specific environment variable is present: PHP_IDE_CONFIG. This contains the server name to be used, which PhpStorm maps to the configured servers for your project.

An example value would be

PHP_IDE_CONFIG=serverName=myproject.ddev.local

Now, you could export this every time you want to profile a PHP script over the command line -- but that is tedious. To ensure this variable is always present, I use an environments file for DDEV. To do this, create a docker-compose.env.yaml file in your .ddev directory. DDEV will load this alongside its main Docker Composer file and merge it in.

version: '3.6'

services:
  web:
    environment:
    - PHP_IDE_CONFIG=serverName=myproject.ddev.local

And now you can have PHP scripts over the command line trigger step debugging via Xdebug!