saahityaedams

28 Aug 2021

Simple Drupal 7 Shell

Problem

For debugging drupal 7 code, there is no packaged shell like django or ROR and we must start a normal PHP interactive shell and then initialize and bootstrap the DRUPAL installation in the shell. This involves searching and copying the 4 lines of drupal initialization and bootstrapping code from the project and pasting it in the PHP shell before doing any Drupal debugging work.

Solution

PHP CLI has an settings option auto_prepend_file which can be used to run some initialization code before running the PHP interactive shell with php -a. So running

php -a -d auto_prepend_file=/Users/<user-name>/drupal-init.php

with drupal-init.php having

<?php

define ( 'DRUPAL_ROOT', '<project-location>' );
$_SERVER ['REMOTE_ADDR'] = "localhost"; // Necessary if running from command line
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap ( DRUPAL_BOOTSTRAP_FULL );

echo "A Simple Drupal 7 shell\n";

Starts a shell were you can start debugging drupal 7 code right away. You can also put the slightly longer PHP command in the terminal shell config(.bashrc, .zshrc) as an alias like

alias drupal-shell="php -a -d auto_prepend_file=/Users/<user-name>/drupal-init.php"

So you can start the drupal shell with just drupal-shell in the terminal.