Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 291687

How to get database connection in the code? Which method is recomended?

$
0
0

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.

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;

Viewing all articles
Browse latest Browse all 291687

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>