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

Using services in Drupal 8

Before we go and use our service in the Controller we created, let's take a breather and run through the ways you can make use of services once they are registered.

There are essentially two ways--statically and injected. The first is done by a static call to the Service Container, whereas the second uses dependency injection to pass the object through the constructor (or in some rare cases, a setter method). However, let's check out how, why, and what is the real difference.

Statically, you would use the global Drupal class to instantiate a service:

$service = \Drupal::service('hello_world.salutation');

This is how we use services in the .module files and classes, which are not exposed to the Service Container and into which we cannot inject--although the latter instances are rare. A few popular services also have shorthand methods on the \Drupal class, accessing them faster (and easier for IDE autocompletion), for example, \Drupal::entityTypeManager(). I recommend that you inspect the \Drupal class and take a look at the ones with shorthand methods available.

It is not the best practice, and for me, it is personally unacceptable to use the static method of service instantiation inside a Controller, service, plugin or any other class where an injection is an option. The reason is that it defeats much of the purpose of using a service, as it couples the two, and it becomes a nightmare to test. Inside hook implementations and other Drupal-specific procedural code, on the other hand, we have no choice, and it is normal to do so.

Just because a code is inside a .module file, it doesn't mean that it should be there. In general, these modules should only contain things such as hook implementations or any other implementations that require a certain naming convention to be respected. They should also be lean and have their work delegated to services.

The proper way to use services is to inject them where needed. Admittedly, this approach is a bit more time-consuming, but, as you progress, it will become second nature. Also, since there are a few different ways to inject dependencies (based on the receiver), we will not cover them here. Instead, we will see how they work throughout this book, at the right time. We will take a look at a very important example right now in the next section.

主站蜘蛛池模板: 前郭尔| 全椒县| 布拖县| 泾阳县| 措美县| 安陆市| 嘉定区| 怀柔区| 永寿县| 东乌珠穆沁旗| 开江县| 达州市| 清镇市| 繁昌县| 定州市| 喜德县| 泾川县| 沁阳市| 四子王旗| 和平县| 曲松县| 天峨县| 扎鲁特旗| 从化市| 榆中县| 双江| 松江区| 方山县| 盖州市| 永胜县| 工布江达县| 凤山市| 化德县| 印江| 山丹县| 博白县| 阳谷县| 通化市| 杂多县| 千阳县| 溧水县|