- Drupal 8 Module Development
- Daniel Sipos
- 397字
- 2021-07-02 15:45:15
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.
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.
- Microsoft Application Virtualization Cookbook
- Java面向?qū)ο笏枷肱c程序設(shè)計
- Apache Spark 2.x Machine Learning Cookbook
- 深入淺出Java虛擬機(jī):JVM原理與實戰(zhàn)
- Julia機(jī)器學(xué)習(xí)核心編程:人人可用的高性能科學(xué)計算
- Mastering LibGDX Game Development
- Web程序設(shè)計(第二版)
- Highcharts Cookbook
- Scala程序員面試算法寶典
- 圖數(shù)據(jù)庫實戰(zhàn)
- 智能手機(jī)APP UI設(shè)計與應(yīng)用任務(wù)教程
- Python:Deeper Insights into Machine Learning
- Raspberry Pi Robotic Projects(Third Edition)
- TypeScript 2.x By Example
- Building Slack Bots