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:
- In the tests,
\Drupal::database()
and$this->connection
: - In the tests,
Database::getConnection()
and$this->connection
:
https://cgit.drupalcode.org/drupal/tree/core/tests/Drupal/KernelTests/Co... even injected connection inherited from\Drupal\KernelTests\Core\Database\DatabaseTestBase
With procedural code situation is pretty clear - use \Drupal::database()
Remaining tasks
- discuss
- determine which method is preferred in a particular situation.
Proposed resolution
-
In OOP code:
- If it possible, use DI to use
@database
service or$container->get('database');
to inject the database connection - If not possible (as in a static method of a class), use
\Drupal::database()
. - If services are not yet available,
\Drupal\Core\Database\Database::getConnection()
can get a database connection. - 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.
- 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.
- If it possible, use DI to use
-
In the Procedural code, i.e.
*.module
,*.inc
or script files:- Use
\Drupal::database();
to get database connection;
- Use