Document the recommended ways to obtain the database connection object

Created on 8 August 2018, over 6 years ago
Updated 22 August 2024, 4 months ago

Problem/Motivation

Follow-up: #2853118-57: Replace all calls to db_insert, which is deprecated โ†’

We have different methods of how to get the connection to the database that currently used in the different places of the codebase.

We need to determine which method is preferred in a particular situation.

For example:

With procedural code situation is pretty clear - use \Drupal::database()

Remaining tasks

- discuss
- determine which method is preferred in a particular situation.
Make a follow up - See #13 ๐Ÿ“Œ Document the recommended ways to obtain the database connection object Needs work

Proposed resolution

  1. In OOP code:
    1. If it possible, use DI to use @database service or $container->get('database'); to inject the database connection
    2. If not possible (as in a static method of a class), use \Drupal::database().
    3. If services are not yet available, \Drupal\Core\Database\Database::getConnection() can get a database connection.
    4. In unit tests, we do not have a booted kernel or a built container. Unit tests should generally not access a database. A unit test which need a database service should be converted to a kernel test.
    5. In kernel and functional test classes we have $this->container->get('database'). Some test authors might discover that the container referenced by the test class will be out of sync with the current container during the request in a functional test. In that circumstance, a test author might call $this->rebuildContainer() and then access $this->container->get('database') again.
  2. In the Procedural code, i.e. *.module, *.inc or script files:
    1. Use \Drupal::database(); to get database connection;
๐Ÿ“Œ Task
Status

Fixed

Version

11.0 ๐Ÿ”ฅ

Component
Documentationย  โ†’

Last updated about 2 hours ago

No maintainer
Created by

๐Ÿ‡บ๐Ÿ‡ฆUkraine voleger Ukraine, Rivne

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024