Core API

by Gisle Hannemyr

Mumble

Table of contents

Introduction

In Drupal 7 (and earlier) if you wanted to use code that lived somewhere in your project, and there was no hook or API call for it, you had to replicate that code in your own code. This lead to a lot of duplicated code, which then at to maintained seperately and over time would disintegrate.

OOP lets you easily pull code from elsewhere in the project (meaning that you aren't actually copying code, you're reusing an existing instance of it). You can use it as is, or if it does most of what you want, you can override some parts (so that you can just tweak a few things without having to duplicate it whole thing first.

Sources:

Calling a core method

In this example, we shall call public function DrupalTranslator::getLocale. Start out by loocing at the API documentation to determine the Class and Namespace:

Class
DrupalTranslator
Namespace
Drupal\Core\Validation

If it is not outloaded, make "use" declaration by concatenating the Namespace and Class:

use Drupal\Core\Validation\DrupalTranslator;

If the method is not static, it cannot be called without first creating an object, so this is how the call should be executed:

$translator = new DrupalTranslator();
$locale = $translator->getLocale();  

entityQuery

entityQuery allows developers to query Drupal entities and fields in a SQL-like way. A Drupal site's tables and fields are never a 1-to-1 match for the site's entities and fields – entityQuery allows us to query the database as if they were 1-to-1.

// Check if user owns any nodes.
$uid = $account->id();
$nids = \Drupal::entityQuery('node')
  ->condition('uid', $uid)
  ->accessCheck(FALSE)
  ->execute();
dpm($nids, 'nids');

This blog post by Michael Anello provide an introduction to entityQuery: entityQuery examples for everybody.

Final word

[TBA]


Last update: 2022-04-03 [gh].