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!

require_once './includes/';

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.


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();
      require_once 'core/includes/';
      Settings::initialize($app_root, $this->kernel->getSitePath(), $classloader);
      $this->container = $this->kernel->getContainer();
    return $this;