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
parent
d43e2ba8f3
commit
bd4a29dada
|
@ -239,6 +239,53 @@ use Drupal\Core\Database\Query\SelectInterface;
|
||||||
* @endcode
|
* @endcode
|
||||||
* if you had a connection object variable $connection available to use. See
|
* if you had a connection object variable $connection available to use. See
|
||||||
* also the @link container Services and Dependency Injection topic. @endlink
|
* 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 https://www.drupal.org/docs/drupal-apis/database-api
|
||||||
* @see entity_api
|
* @see entity_api
|
||||||
|
|
Loading…
Reference in New Issue