Now that we have some tables to work with, let's take a look at how we can run queries against them. If you are following along, for testing purposes, feel free to add some dummy data into the tables via the database management tool of your choice.
We will look at INSERT statements soon, but before that, we will need to talk about the more common types of queries you'll run--SELECT. Queries using the Drupal 8 database abstraction layer are run using a central database connection service--database. Statically, this can be accessed via a shortcut:
$database = \Drupal::database();
This service is a special one compared to the ones we saw before, because it is actually created using a factory:
database:
class: Drupal\Core\Database\Connection
factory: Drupal\Core\Database\Database::getConnection
arguments: [default]
This is a definition by which the responsibility for the instantiation is delegated to the factory mentioned, instead of the container as we've seen before. So, the resulting class does not necessarily need to match the one specified for the class key. However, in this case, the
Drupal\Core\Database\Connection is an abstract base class that the resulting service extends.
Again, in this case, the arguments are responsible for specifying the type of connection that it has to create. The site-default type is used (MySQL, usually), which means that the resulting service will be an instance of Drupal\Core\Database\Driver\mysql\Connection. From this connection service, we can then request the relevant object with which we can build queries. So, let's see how these work.
No comments:
Post a Comment