The HelloWorldSalutation service

Now that we have a general idea as to what a service is, let's create one to see all this in practice.

As I mentioned earlier, I want my greetings to be more dynamic, that is, I want the salutation to depend on the time of day. So, we will create a (HelloWorldSalutation) class that is responsible for doing that and place it in the /src folder (or module’s namespace root):

namespace Drupal\hello_world;use Drupal\Core\StringTranslation\StringTranslationTrait;/** * Prepares the salutation to the world. */class HelloWorldSalutation {  use StringTranslationTrait;  /**   * Returns the salutation   */  public function getSalutation() {    $time = new \DateTime(); if ((int) $time->format('G') >= 06 && (int) $time->format('G') ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.