Skip to main content
Boots on stairs

Bootstrapping Drupal inside another Composer project

Now that Drupal has "left the island" and embraced dependency management a la Composer, how can we bootstrap Drupal 8 inside another PHP application?

Before Drupal incorporated dependency management, OOP and Symfony components, boostrapping the D7 codebase was as easy as:

D7 bootstrap!
Code

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Things aren't as simple in Drupal 8, but after reviewing the inline code documentation and taking a lead from Drush, I've arrived at the following. The key is prepareLegacyRequest(), which, despite being marked as deprecated for Drupal 9, helps us load Drupal without having to fully process a request object.

Code

class WorksWithDrupal {
  /**
   * Bootstrap Drupal.
   * @see index.php
   */
  private function bootstrap() {
    try {
      $this->container = \Drupal::getContainer();
    }
    catch (Exception $e) {
      $autoloader = '../autoload.php';
      if (file_exists($autoloader)) {
        $classloader = require $autoloader;
      }
      $request = Request::createFromGlobals();
      $request->server->set('SCRIPT_FILENAME', '/');
      $this->kernel = new DrupalKernel('prod', $classloader);
      $app_root = $this->kernel->getAppRoot();
      chdir($app_root);
      require_once 'core/includes/bootstrap.inc';
      $this->kernel->setSitePath($this->kernel->findSitePath($request));
      Settings::initialize($app_root, $this->kernel->getSitePath(), $classloader);
      $this->kernel->invalidateContainer();
      $this->kernel->prepareLegacyRequest($request);
      chdir($pwd);
      $this->container = $this->kernel->getContainer();
    }
    return $this;
  }
}

Photo