官术网_书友最值得收藏!

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') < 12) {
return $this->t('Good morning world');
}

if ((int) $time->format('G') >= 12 && (int) $time->format('G') < 18) {
return $this->t('Good afternoon world');
}

if ((int) $time->format('G') >= 18) {
return $this->t('Good evening world');
}
}
}

By now, I assume that the namespace business is clear, so I won't explain it again. Let's see what else we did here. First, we used the StringTranslationTrait in order to expose the translation function (I will explain this later on). Second, we created a rudimentary method that returns a different greeting depending on the time of day. This could probably have been done better, but for the purposes of this example, it works just fine.

If there is any reason to believe that you will have more than one salutation services, you should create an interface this class can implement. This way, you'll be able to always type hint that interface instead of the class and make the implementations swappable.

Now that we have our class, it's time to define it as a service. We don't want to be going all new HelloWorldSalutation() all over our code base, but instead, register it with the Service Container and use it from there as a dependency. How do we do that?

First, we will need, yet again, a YAML file in our hello_world.services.yml module. This file starts with the services key, under which will be all the service definitions of our module. So, our file will look like this (for now):

services:
hello_world.salutation:
class: Drupal\hello_world\HelloWorldSalutation

This is the simplest possible service definition you can have. You give it a name (hello_world.salutation) and map it to a class to be instantiated. It is a standard practice to have the service name start with your module name.

Once we clear the cache, the service will get registered with the Service Container and will be available to use.

主站蜘蛛池模板: 盐源县| 托克托县| 平湖市| 南乐县| 富锦市| 新田县| 皋兰县| 定结县| 桓仁| 东乡县| 嘉祥县| 新丰县| 海盐县| 桑植县| 保靖县| 东安县| 阿拉善盟| 诸城市| 潜山县| 舞钢市| 社旗县| 定远县| 维西| 天全县| 安远县| 临洮县| 武隆县| 孟津县| 塘沽区| 巫山县| 康平县| 鹤山市| 徐州市| 尤溪县| 汕尾市| 安达市| 类乌齐县| 怀来县| 桐柏县| 沛县| 若羌县|