Issue #2991337 by voleger, quietone, Marios Anagnostopoulos, andypost, Mile23, mondrake, smustgrave, cilefen, alexpott, catch, TR: Document the recommended ways to obtain the database connection object

merge-requests/6065/head^2
nod_ 2024-08-08 16:16:45 +02:00
parent d43e2ba8f3
commit bd4a29dada
No known key found for this signature in database
GPG Key ID: 76624892606FA197
1 changed files with 47 additions and 0 deletions

View File

@ -239,6 +239,53 @@ use Drupal\Core\Database\Query\SelectInterface;
* @endcode
* if you had a connection object variable $connection available to use. See
* also the @link container Services and Dependency Injection topic. @endlink
* In Object Oriented code:
* - If possible, use dependency injection to use the "database" service.
* @code
* use Drupal\Core\Database\Connection;
*
* class myClass {
*
* public function __construct(protected Connection $database) {
* // ...
* }
* @endcode
* - If it is not possible to use dependency injection, for example in a static
* method, use \Drupal::database().
* @code
* $connection = \Drupal::database();
* $query = $connection->query('...');
* @endcode
* - If services are not yet available, use
* \Drupal\Core\Database\Database::getConnection() to get a database
* connection;
* @code
* use Drupal\Core\Database\Database;
*
* // ...
*
* $connection = Database::getConnection();
* $query = $connection->query('...');
* @endcode
* - In unit tests, we do not have a booted kernel or a built container. Unit
* tests that need a database service should be converted to a kernel test.
* - In kernel and functional test classes, use
* \Drupal\Core\Database\Database::getConnection() to get a database
* connection.
* @code
* use Drupal\Core\Database\Database;
*
* // ...
*
* $connection = Database::getConnection();
* $query = $connection->query('...');
* @endcode
* In procedural code, such as *.module, *.inc or script files:
* - Use \Drupal::database(); to get database connection.
* @code
* $connection = \Drupal::database();
* $query = $connection->query('...');
* @endcode
*
* @see https://www.drupal.org/docs/drupal-apis/database-api
* @see entity_api