Question

How can I bootstrap Drupal 8 from an external script?

This an example script from the RabbitMQ Work Queues tutorial.

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('task_queue', false, true, false, false);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) {
  echo ' [x] Received ', $msg->body, "\n";
  sleep(substr_count($msg->body, '.'));
  echo " [x] Done\n";
  $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};

$channel->basic_qos(null, 1, null);
$channel->basic_consume('task_queue', '', false, false, false, false, $callback);

while (count($channel->callbacks)) {
  $channel->wait();
}

$channel->close();
$connection->close();

Within a worker script like this, I need to be able to create nodes.

How can I bootstrap Drupal 8 in this script?

Php Access User Data from external script? and Bootstrap from external script bootstraps passing a fake request to the kernel, which to me looks like a work-around.

In Drupal 7 you could do something like this, apparently.

// Bootstrap Drupal.
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
Was it helpful?

Solution

I ended up inheriting the kernel and will adjust it as needed be.

Something like:

namespace Drupal\Core;

use Drupal\Core\Site\Settings;

class DrupalCliKernel extends DrupalKernel {

  public function bootstrap() {
    static::bootEnvironment();
    $this->setSitePath('sites/default');
    Settings::initialize($this->root, 'sites/default', $this->classLoader);
    $this->boot();
  }

}

And then:

use Drupal\Core\DrupalCliKernel;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalCliKernel('prod', $autoloader);
$kernel->bootstrap();

// Drupal is bootstrapped now.

Not yet sure if I miss something important, but I am most likely not using this, but instead relying on using HTTP requests that the worker will use as Drupal is too coupled to the HTTP request. Just putting it out if someone come here to try to accomplish something similar and want a jump-start.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top