0

Drupal 7 had a neat feature of different bootstrap levels that allowed to write really fast micro services that didn't require to fully bootstrap Drupal.

Drupal bootstrap levels no longer exists in Drupal 8, but what would be the best approach to build some kind of microkernel to handle simple database queries? I'd like to initialize the database and configuration to do some SQL queries and send a JSON response.

7

A lot of the bootstrap process happens now implicitly as services are requested.

If nothing requests the database service then Drupal won't open the connection to it and so on.

The minimal amount of code to do a custom php file that bootstraps Drupal and does some queries can be seen in statistics.php:

$autoloader = require_once 'autoload.php';

$kernel = DrupalKernel::createFromRequest(Request::createFromGlobals(), $autoloader, 'prod');
$kernel->boot();
$container = $kernel->getContainer();

$views = $container
  ->get('config.factory')
  ->get('statistics.settings')
  ->get('count_content_views');

if ($views) {
  $nid = filter_input(INPUT_POST, 'nid', FILTER_VALIDATE_INT);
  if ($nid) {
    $container->get('request_stack')->push(Request::createFromGlobals());
    $container->get('statistics.storage.node')->recordView($nid);
  }
}

Depending on what it is for, you could also do a normal controller and return a cacheable JsonResponse with the right cache tags and contexts, then Drupal will automatically cache that in the internal and dynamic page cache. Which, depending on your queries, might not be much or not at all slower.

  • Thanks that sounds promising. The main issue here is that I can't cache response but in other hand all I need to generate it is one SQL query. That's why I thought of this micro kernel approach to reduce unnecessary overhead. – SiliconMind May 22 '17 at 20:28
  • Why can't it be cached? – Berdir May 22 '17 at 22:27
  • Because response depends on one of the request headers and varies between anonymous users. – SiliconMind May 23 '17 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.