So I was making a custom block, and implemented the build() method.
public function build() {
$result = $connection->db_query("SELECT n.title, u.uid, n.created FROM node_field_data n, users u WHERE u.uid = n.uid AND n.type = :type ORDER BY n.created DESC LIMIT 5", array(
'type' => 'article',
));
$content = '';
if ($result) {
while ($row = $result->fetchAssoc()) {
$content .= '<li>' . $row['title'] . '</li>';
}
} else {
$content .= 'No blog posts to show';
}
return array(
'#markup' => '<ul>' . $content . '</ul>',
);
}
So this is a pretty basic helloworld kind of example calling the database. But db_query is deprecated with the following surgestion:
* @deprecated as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get
* a database connection injected into your service from the container and
* call query() on it. E.g.
* $injected_database->query($query, $args, $options);
The surgestion seemed kind of spacey not entirely knowing all of the expressions but i eventually fixed it with the following code:
$connection = \Drupal::database();
$result = $connection->query("SELECT n.title, u.uid, n.created FROM node_field_data n, users u WHERE u.uid = n.uid AND n.type = :type ORDER BY n.created DESC LIMIT 5", array(
'type' => 'article',
));
to call the database.
My question is, \Drupal::database() is a static method, and i call it from inside of my own block, am i doing it wrong? or am i misunderstanding their meaning of dependency injection? if i had to do DI in other web programming i would find the DI container and configure it to give the database into my constructor or via a accessor method right?
Follow up questions is
What exactly constitutes my container?
What is "my service" referring to? my module maybe?